Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP in_array wildcard match

Tags:

php

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?

like image 276
user4424340 Avatar asked Mar 17 '23 10:03

user4424340


1 Answers

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";
}
like image 175
Tryth Avatar answered Mar 31 '23 02:03

Tryth