簡體   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