String contains any items in an array (case insensitive)

tarnfeld picture tarnfeld · Jan 23, 2010 · Viewed 48k times · Source

How can i check if a $string contains any of the items expressed in an array?

$string = 'My nAmE is Tom.';
$array = array("name","tom");
if(contains($string,$array))
{
// do something to say it contains
}

Any ideas?

Answer

zombat picture zombat · Jan 23, 2010

I don't think there is a built-in function that will handle what you want. You could easily write a contains() function however:

function contains($str, array $arr)
{
    foreach($arr as $a) {
        if (stripos($str,$a) !== false) return true;
    }
    return false;
}