Does array element contain substring?

Isaiah picture Isaiah · Oct 27, 2013 · Viewed 14.4k times · Source

I'd like a function that checks whether an array's items contain a string. As such:

array(1 => 'Super-user', 'Root', 'Admin', 'Administrator', 'System', 'Website', 'Owner', 'Manager', 'Founder');

And then checking for admin12 should return true as a part of admin12 (admin) is also a part of the array.

I came this far:

$forbiddennames= array(1 => 'Super-user', 'Root', 'Admin', 'Administrator', 'System', 'Website', 'Owner', 'Manager', 'Founder');    

if(in_array( strtolower($stringtocheck), array_map('strtolower', $forbiddennames))){
        echo '"This is a forbidden username."';
    } else {
        echo 'true';
    }
}

Only this only echos "This is a forbidden username." when I check for admin. I want it also to echo when checking for admin12.

Is this possible (and how)?

Answer

Amal Murali picture Amal Murali · Oct 27, 2013

Loop through the $forbiddennames array and use stripos to check if the given input string matches any of the items in the array:

function is_forbidden($forbiddennames, $stringtocheck) 
{
    foreach ($forbiddennames as $name) {
        if (stripos($stringtocheck, $name) !== FALSE) {
            return true;
        }
    }
}

And use it like below:

if(is_forbidden($forbiddennames, $stringtocheck)) {
    echo "This is a forbidden username.";
} else {
    echo "True";
}

Demo!