PHP Function to Check Bad Words

Joined
Nov 20, 2010
Messages
37
Reaction score
2
Code:
<?php
function isBadWord($text)
{

//First we list the bad words in array
$badwords = array(
'truck',
'hi',
'lie',
'bad',
'night',
'eg'
);

//Then we perform the bad word check
foreach($badwords as $badwords)
{
if(stristr($text,$badwords))
{
return true;
}
}
return false;
}
?>

First we need to list the bad words in an array. Then we perform the check using the stristr function which searches for the bad words inside the given text.

If no bad word is found it returns FALSE.

Here is an example of how to use this function

Code:
<?php

$text = '';� //Put your text here to check

if(isBadWord($text))
{
echo 'Bad Word Found!';
}
else
{
echo 'No Bad Word!';
}

?>
 
you don't need to do the loop...
you can search for any word inside the array directly.
its way faster than the looping..
 
Another way to do it
PHP:
$badWords=array("badword","anotherbadword");
$replacements=array("goodword","anothergoodword");
$fixed=str_ireplace($badWords,$replacements,$string);
 
Another way to do it
PHP:
$badWords=array("badword","anotherbadword");
$replacements=array("goodword","anothergoodword");
$fixed=str_ireplace($badWords,$replacements,$string);
neat solution :cool:
 
This type of script is also good for turning keywords into interlinks like wikipedia does.

I use it on all my static sites.

Damn I love PHP :)
 
This type of script is also good for turning keywords into interlinks like wikipedia does.

I use it on all my static sites.

Damn I love PHP :)
PHP was my first love :D
I've worked with asp.net and php before.. but damn man php is way way better for developing web apps..
 
you don't need to do the loop...
you can search for any word inside the array directly.
its way faster than the looping..

What do you mean by this? Either I've lost you or you've misunderstood the OP. She's iterating through a list of words and testing a text body to see if each one might be in there. Beside the str_replace() solution (preg_* could be used the same), how do you suggest doing it without a loop?

And speaking of preg_*, if you use a regular expression approach (which, mind you, is computationally more expensive, but usually not enough to notice), you can get better at finding variations that users use to get around the list of bad words. You can see if bad words are included inside of others, used on their own, had letters replaced with numbers, had punctuation or spaces inserted in them, and lots more.

Moreover, this kind of simple filtering may get some of the easy stuff, but if you really want to get the hard stuff, I'd suggest hitting up the PHP manual for the functions similar_text, metaphone, levenshtein and soundex.

Last, I just want to throw in my opinion that censoring free speech sux. ;)
 
Back
Top