5

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?

user4424340
  • 59
  • 1
  • 2

4 Answers4

4

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";
}
Community
  • 1
  • 1
Tryth
  • 411
  • 2
  • 11
4

By filtering each word in array with case insensitive regex , you can get the list of words contains needle.

<?php
$haystack = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
$needle = 'DAY';
$matches = array_filter($haystack, function($var){return (bool)preg_match("/$needle/i",$var);});
print_r($matches);

outputs :

Array
(
    [0] => sunday
    [1] => monday
    [2] => tuesday
    [3] => wednesday
    [4] => thursday
    [5] => friday
    [6] => saturday
)
xdebug
  • 1,178
  • 12
  • 16
1
$example = array('An example','Another example','One Example','Last example');
$searchword = 'last';
$matches = array();
foreach($example as $k=>$v) {
    if(preg_match("/\b$searchword\b/i", $v)) {
        $matches[$k] = $v;
    }
}

Works with substrings and case insensitive.

Found here: Search for PHP array element containing string

Community
  • 1
  • 1
manuelbcd
  • 3,106
  • 1
  • 26
  • 39
0

You can do with strtolower()

$words = array('i', 'am', 'very', 'bad');

$username = "VeRy";
$un = strtolower($username);

if (in_array($un, $words)){
    //found !
}
Spoke44
  • 968
  • 10
  • 24