PHP检查一个长单词字符串中的多个单词


PHP checking multiple words in a long one word string

使用strpos,我可以在一个字符串中找到一个单词,但如何找到多个单词?

当字符串包含用空格分隔的单词时,我知道如何执行此操作,但例如,如果我有array('hi','how','are','you')和字符串$string = 'hihowareyoudoingtoday?'如何返回找到的匹配的总金额?

您可以使用返回匹配数的preg_match_all

$words = array('hi','how','are','you');
$nb = preg_match_all('~' . implode('|', $words) . '~', $string, $m);
print_r($m[0]);
echo "'n$nb";

preg_match_all是一个函数,用于搜索字符串中出现的所有模式。在本例中,模式为:

~hi|how|are|you~

CCD_ 5仅仅是模式定界符。

|是逻辑OR

请注意,搜索是从字符串中的左到右逐个字符执行的,并且测试每个备选方案,直到其中一个匹配为止。因此,在某个位置匹配的第一个单词被存储为匹配结果(到$m中)。了解这种机制很重要。例如,如果您有字符串baobab和模式~bao|baobab~,则结果将仅为bao,因为它是第一个测试的备选方案。

换句话说,如果您想首先获得最大的单词,则需要在之前按大小对数组进行排序。

是的,在这种情况下可以使用strpos()

示例:

$haystack = 'hihowareyoudoingtoday?';
$needles = array('hi','how','are','you');
$matches = 0;
foreach($needles as $needle) { // create a loop, foreach string
    if(strpos($haystack, $needle) !== false) { // use stripos and compare it in the parent string
        $matches++; // if it matches then increment.
    }
}
echo $matches; // 4