Hi all , this is our first post in the “PHP quick lessons” series .In this post we will be creating a small fun word censoring program with php.
Word censoring is hiding unacceptable words from the audience.For eg.(idiot → *****)
A basic use case could be a forum or a website where other anonymous users can comment.
To do this you will require to have some basic knowledge of php and html forms.
Lets first create a simple form which will accept user input.
Check out the demo here : Word Censor using PHP
Submit method can be GET or POST but usually user would be posting lots of data to so POST should be prefered .
Now lets write a php script that will retrieve the user entered data(on the same page)
This will print the data onto the page but wait thats not enough, lets add some validations to it.
I’ve added inline comments to help you understand the use of each ‘if’ loop.
Now lets create an array that will hold the list of words to be censored .
$list = array('idiot','noob','Geek');
$replace = array('i***t','**ob','****');
We will declare these at the top.
To accomplish our mission we will be using str_replace() function no actually str_ireplace().
The difference between the two is that the later is case insensitive.Lets move ahead and finish what we started .So our final code will look like this.
(Copy paste the above code into a php file and run it on a server or local server(xampp) with php installed)
Explanation for str_ireplace($list,$replace,$usercomment);
$list = list of words to be censored;
$replace = List of corresponding censored words.
$usercomment = string to be operated (In our case our user input.)
Of-course this is a basic example of how the sr_ireplace function works but can be used in may other cases.