确定数组中的哪个单词在字符串中

时间:2015-03-01 18:01:05

标签: php

我有一个字符串:

$str = "Hello is a greeting";

我有一系列的话:

$equals = array("is", "are", "was", "were", "will", "has", "have", "do", "does");

我正在尝试查看字符串中的哪个单词:

$words = explode(" ", $str);
$new_association = false;
foreach($words as $word) {
    if(in_array($word, $equals)) {
        $new_association = true;
        $e['response'] = 'You made an association.';
        // determine which 'equals' word was used.      
        // $equal_used = 'is';
    }
}

如何确定使用了哪个等于字?

2 个答案:

答案 0 :(得分:2)

$new_asscociation = false;
$equal_used = array_intersect($equals, explode(' ', $str)); 
if (!empty($equal_used)) { 
    $new_asscociation = true; 
    var_dump($equal_used); 
}

答案 1 :(得分:0)

马克上面的答案是优越的,但如果你更愿意坚持现有的方法:

$words = explode(" ", $str);
$new_association = false;
foreach($words as $word) {
    if(in_array($word, $equals)) {
        $new_association = true;
        $e['response'] = 'You made an association.';
        // determine which 'equals' word was used.      
        $equal_used = $word;
    }
}