繁体   English   中英

正则表达式在php中匹配字符串中的两个(或更多)单词

[英]Regexp in php matching two (or more) words in string

我要做的是检查字符串中是否存在某些关键字。 匹配单个单词不是问题,但是如果例如两个单词需要匹配,我无法弄清楚如何使它工作。

这是我到目前为止所得到的

$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";
    }
}

问题是我不知道如何创建一个正则表达式,如果stringchecked都匹配,则返回true。 如果我需要使用两个不是问题的表达式。

作为一个逻辑陈述,它将是这样的: single || bar || (string && checked) 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做这个,你可以使用:

$regex = "";
foreach ($filter as $word) {
    $regex .= "(?=.*\b".$word."\b)";
}
$regex = "/".$regex."^.*$/i";

对于单词singlebar正则表达式生成是: /(?=.*\\bsingle\\b)(?=.*\\bbar\\b)^.*$

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

$matchFound = preg_match($regex, $text);
print($matchFound); // 0 for "single","bar". 1 for "single","checked"

维护您的实际代码可能是一种探索方式,检查数组是否与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) {
    ...

!!array_diff如果没有差异, !!array_diff返回false,这意味着在$text中找到$filter所有键

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM