Although the other answers use regex and the preg_*
family, you're probably better off using stripos()
, as it is bad practice to use preg_*
functions just for finding whether something is in a string - stripos
is faster.
However, stripos
does not take an array of needles, so I wrote a function to do this:
function stripos_array($haystack, $needles){
foreach($needles as $needle) {
if(($res = stripos($haystack, $needle)) !== false) {
return $res;
}
}
return false;
}
This function returns the offset if a match is found, or false otherwise.
Example cases:
$foo = 'evil string';
$bar = 'good words';
$baz = 'caseBADcase';
$badwords = array('bad','evil');
var_dump(stripos_array($foo,$badwords));
var_dump(stripos_array($bar,$badwords));
var_dump(stripos_array($baz,$badwords));
# int(0)
# bool(false)
# int(4)
Example use:
if(stripos_array($word, $evilwords) === false) {
echo "$word is fine.";
}
else {
echo "Bad word alert: $word";
}