I have a bunch of banned words and want to check if string A contains any of these words.
For example:
$banned_words = \"dog cat horse bird mouse mon
$badwords = array('dog','cat','horse','bird','mouse','monkey');
$content= "The quick brown fox jumped over the lazy dog";
$content = str_replace($badwords, 'has_badwords' $content);
if (strpos($content, 'has_badwords') !== false) {
echo 'true';
}
It would be a whole lot easier to create an array of banned words and then use str_replace
with that array, like so:
$banned_words = array('dog', 'cat', 'horse', 'bird', 'mouse', 'monkey', 'blah', 'blah2', 'blah3');
$string_A = "The quick brown fox jumped over the lazy dog";
echo str_replace($banned_words, "***", $string_A);
Will output: The quick brown fox jumped over the lazy ***
I just developed a function that can filter out the bad words:
function hate_bad($str)
{
$bad=array("shit","ass");
$piece=explode(" ",$str);
for($i=0;$i < sizeof($bad); $i++)
{
for($j=0;$j<sizeof($piece);$j++)
{
if($bad[$i]==$piece[$j])
{
$piece[$j]=" ***** ";
}
}
}
return $piece;
}
and call it like this:
$str=$_REQUEST['bad'];// here bad is the name of tex field<br/><br/>
$good=hate_bad($str); <br/>
if(isset($_REQUEST['filter']))// 'filter' name of button
{
for($i=0;$i<sizeof($good);$i++)
{<br/>
echo $good[$i];
}
}
Wouldn't it be better if the $banned_w
would be an array?
Then you could explode()
the string you want to check for banned words, then for every exploded piece use in_array()
to check if it's a banned word.
Edit: You could use: similar_text for the comparisons, if one modifies the bad word a bit.
if (preg_match('~\b(' . str_replace(' ', '|', $banned_words) . ')\b~', $string_A)) {
// there is banned word in a string
}
You can use str_ireplace, to check for bad words or phrases. This can be done in a single line of PHP code without the need for nested loops or regex as follows:
$banstring = ($string != str_ireplace($badwords,"XX",$string))? true: false;
This approach has the added benefit of being case insensitive. To see this in action, you could implement the check as follows:
$string = "The quick brown fox jumped over the lazy dog";
$badwords = array('dog','cat','horse','bird','mouse','monkey');
$banstring = ($string != str_ireplace($badwords,"XX",$string))? true: false;
if ($banstring) {
echo 'Bad words found';
} else {
echo 'No bad words in the string';
}
If the list of bad words is a string rather than an array (as in the question), then the string can be turned into an array as follows:
$banned_words = "dog cat horse bird mouse monkey"; //etc
$badwords = explode(" ", $banned_words);