views:

313

answers:

5

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?

A: 

Will this do the job?

$words = explode(" ", $string);
$wordsInArray = array();
foreach($words as $word) {
    if(in_array($word, $array)) {
        $wordsInArray[] = $word;
    }
}
robertbasic
+1  A: 

is that what you wanted? i hope that code is compiling :)

$string = 'My nAmE is Tom.';
$array = array("name","tom");
if(0 < count(array_intersect(array_map('strtolower', explode(' ', $string)), $array)))
{
  //do sth
}
tomaszsobczak
this seems to work the best between them all :)
tarnfeld
This would fail on the strings: "Tom, what do you think?" "His 'name' is Tom." among many others.
hobodave
+1  A: 

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;
}
zombat
+1 for not being ridiculously complex, using regexes, or trying to fit it all in one line.
hobodave
+1  A: 

Something like this would work:

$string = 'My nAmE is Tom.';
$array = array("name", "tom");
foreach ($array as $token) {
    if (stristr($string, $token) !== FALSE) {
        print "String contains: $token\n";
    }
}
Paul Osman
A: 
function contains($str, $arr)
{
  $ptn = '';
  foreach ($arr as $s) {
    if ($ptn != '') $ptn .= '|';
    $ptn .= preg_quote($s, '/');
  }
  return preg_match("/$ptn/i", $str);
}

echo contains('My nAmE is Tom', array('name', 'tom'));
jspcal