I am storing a list of prohibited words in an array:
$bad = array("test");
I am using the below code to check a username against it:
if (in_array ($username, $bad))
{
//deny
}
but I have a problem in that it only denies if the given username is exactly test, but I want it to also deny if the given username is Test, or TEST, or thisisatestok, or ThisIsATestOk.
Is it possible?
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With