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
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);