Welcome to the first post in our “PHP Quick Lessons” series. In this tutorial, we’ll be creating a fun, small word censoring program using PHP. Word censoring is the process of hiding unacceptable or offensive words from the audience. For example, the word ‘idiot’ might be censored as ‘*****’. This functionality can be particularly useful in environments such as forums or websites where anonymous users can leave comments.
To follow along with this tutorial, you should have some basic knowledge of PHP and HTML forms.
Table of Contents
ToggleCreating a User Input Form
First, let’s create a simple form that will accept user input. The form’s submit method can be either GET or POST, but since users might be posting a lot of data, the POST method is generally preferred. You can check out a demo of the word censoring program here.
Writing a PHP Script to Retrieve User Data
Next, we’ll write a PHP script that retrieves the data entered by the user. Initially, this script will simply print the data onto the page. However, to make our program more robust, we’ll add some validations to the script. Inline comments have been added to the code to help you understand the use of each ‘if’ loop.
Creating a List of Words to Be Censored
Now, let’s create an array that will hold the list of words to be censored. For example:
$list = array('idiot','noob','Geek');
$replace = array('i***t','**ob','****');
These arrays should be declared at the top of your script.
Using the str_ireplace() Function
To replace the words in our list with their censored counterparts, we’ll use the str_ireplace()
function. This function is case-insensitive, unlike the str_replace()
function.
Here’s what the function looks like:
str_ireplace($list,$replace,$usercomment);
In this function:
$list
is the list of words to be censored.$replace
is the list of corresponding censored words.$usercomment
is the string to be operated on (in our case, the user input).
This is a basic example of how the str_ireplace()
function works, but it can be used in many other cases.
Final Code
Here’s what the final code for our word censoring program looks like:
// Copy and paste the above code into a PHP file and run it on a server or local server (like XAMPP) with PHP installed.
By following this tutorial, you’ve learned how to create a basic word censoring program using PHP. This is a fun and practical way to get more familiar with PHP and its capabilities.