PHP检查第一次出现的数组是否存在于另一个数组中

时间:2015-01-30 21:07:19

标签: php arrays

我有两个数组

$setWords = array ('one','two','three');
$setSentences = array('There is one cloud in the sky', 'A dog has four legs' , 'There are three cars parked outside');

我尝试了以下但是它没有用。

if(array_intersect($setWords , $setSentences) == true) {
print_r($setSentences);
}

在这种情况下,它将是There is one cloud in the skyThere are three cars parked outside

2 个答案:

答案 0 :(得分:3)

我爱preg_grep

$result = preg_grep('/'.implode('|', $setWords).'/', $setSentences);
print_r($result);

答案 1 :(得分:2)

这不会奏效。 array_intersect函数仅检查完全相同的值。您需要手动运行数组并使用strpos函数比较内容。

这样的事情:

foreach( $setWords as $word ) {
  foreach( $setSentences as $sentence ) {
    if( strpos( $sentence, $word ) !== false ) {
      echo "found " . $word . " in " . $sentence . "<br />";
    }
  }
}