To follow along with this tutorial, you should have some basic knowledge of PHP and HTML forms.
Creating 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
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.