php中的Regexp匹配字符串中的两个(或更多)单词

php中的Regexp匹配字符串中的两个(或更多)单词,php,regex,Php,Regex,我试图做的是检查字符串中是否存在某些关键字。匹配单个单词不是问题,但是如果两个单词需要匹配,我不知道如何让它工作 这就是我目前得到的 $filter = array('single','bar'); $text = 'This is the string that needs to be checked, with single and mutliple words'; $matches = array(); $regexp = "/\b(" . implode($filter,"|")

我试图做的是检查字符串中是否存在某些关键字。匹配单个单词不是问题,但是如果两个单词需要匹配,我不知道如何让它工作

这就是我目前得到的

$filter = array('single','bar');

$text = 'This is the string that needs to be checked, with single and mutliple words';

$matches = array();

$regexp = "/\b(" . implode($filter,"|") . ")\b/i";

$matchFound = preg_match_all(
                $regexp, 
                $text, 
                $matches
              );


if ($matchFound) {
    foreach($matches[0] as $match) {
        echo $match . "\n";
    }
}
问题是,如果
string
checked
都匹配,我不知道如何创建一个返回true的正则表达式。如果我需要使用两个表达式,那不是问题


作为逻辑语句,它应该是这样的:
single | | bar | | | |(string&&checked)

如果要检查所有单词的出现情况,使用一个变量作为标志就足够了(并独立地检查每个单词),而不是一个大的正则表达式

$filter = array('single','bar');
$foundAll = true;
foreach ($filter as $searchFor) {
    $pattern = "/\b(" . $searchFor . ")\b/i";
    if (!preg_match($pattern, $string)) {
        $foundAll = false;
        break;
    }
}

如果确实希望使用正则表达式执行此操作,可以使用:

$regex = "";
foreach ($filter as $word) {
    $regex .= "(?=.*\b".$word."\b)";
}
$regex = "/".$regex."^.*$/i";
对于单词
single
bar
,生成的正则表达式是:
/(?=.*\b单个\b)(?=.*\bbar\b)^.*$

您不需要循环遍历匹配项,因为这将只匹配一次,并且匹配项将是整个字符串(假设所有单词都存在)


维护实际代码可能是一种探索的方式,检查数组是否与
array_diff
具有相同的值:

$filter = array('single','bar');

$text = 'This is the string that needs to be checked, with single and mutliple words';

$regexp = "/\b(" . implode($filter,"|") . ")\b/i";

$matchFound = preg_match_all($regexp, $text, $matches);

$matchFound = !!array_diff($filter, $matches[1]); //<- false if no diffs

if ($matchFound) {
    ...
$filter=array('single','bar');
$text='这是需要检查的字符串,包含单个和多个单词';
$regexp=“/\b”(.introde($filter,“|”))\b/i”;
$matchFound=preg_match_all($regexp,$text,$matches);

$matchFound=!!数组_diff($filter,$matches[1])//您只想知道字符串中是否包含这些单词,还是打算在以后使用
$matches
呢?不需要。现在我只需要检查单词是否存在问题是(如果我没有弄错的话)它也会匹配bananashake中的香蕉,而这不是我想要的,我只希望整个单词都匹配。@MThomas:在这种情况下,您可以使用
preg_match()
而不是
stripos()
来匹配此代码(并在模式中添加单词边界)(并在第一个false处退出循环)。感谢您的帮助,我成功地实现了这一点。我接受了这一点,因为它为我提供了处理匹配项的选项,现在不需要,但在不久的将来可能会有用。是的,每个
(?=.*\bWORD\b)
都从字符串的开头开始查找。
$filter = array('single','bar');

$text = 'This is the string that needs to be checked, with single and mutliple words';

$regexp = "/\b(" . implode($filter,"|") . ")\b/i";

$matchFound = preg_match_all($regexp, $text, $matches);

$matchFound = !!array_diff($filter, $matches[1]); //<- false if no diffs

if ($matchFound) {
    ...