PHP - Filter Nasty Words

From Global Programming Syntax

Jump to: navigation, search

Sometimes when creating blogs or online communities, you will need to add a word filter to filter nasty words that you don't want search engines indexing. It is a simple process to filter the nasty words and to do so first copy the below code to the top of your php page.

function wordfilter($sentenceb)
{
$nastywords=array('porn','sucks','another_word'); //add more words here
//append to the array above more nasty words.
$iidd=0;
while (isset($nastywords[$iidd]))
{
$sentenceb=str_replace($nastywords[$iidd],'*#!%!#*',$sentenceb);
$iidd+=1;
}
return $sentenceb;
}

So after you have copied the above code into the top of your php page, replace and add to the array in that code (third line) all the words you want filtered. Use the current array as an example of how to set it out and yes you may have as many words as you want. Also note that sometimes you may need to put a space after some of the words inside the array to prevent the replacement from replacing part of a even longer word. But that is if there are any problems with a word being partially replaced and only partically indexed into the array.


Then next is to display the sentence with the filtered words. Below is an example of a sentence being filtered and displayed.

echo wordfilter("The word porn and the word sucks along with many other words will be filtered.");

The above code will display the below:

The word *#!%!#* and the word *#!%!#* along with many other words will be filtered.
Personal tools
languages
page stats
Toolbox