简体   繁体   English

PREG_MATCH检查所有单词和条件

[英]PREG_MATCH check all words and condition

I've written a regular expression which seraches the search terms in OR condition, such that provided three words have in string irrespective of their order. 我写了一个正则表达式,它以OR条件搜索搜索词,使得三个单词都具有字符串形式,而与它们的顺序无关。 Now i want to just put an AND condition as I want to get ALL THREE words simulatniously in a string with different order. 现在,我只想放置一个AND条件,因为我想以不同顺序将所有三个单词同时获得。

Here's my preg_match() regular expresison. 这是我的preg_match()常规表达式。

$myPregMatch = (preg_match("/\b^(Word1|Word2|Word3)\b/", "Word4 Word2 Word1 Word3 Word5 Word7"));
 if ($myPregMatch){
    echo  "FOUND !!!";
 }

I want to find in string "Word4 Word2 Word1 Word3 Word5 Word7" that all words are in it with different order. 我想在字符串"Word4 Word2 Word1 Word3 Word5 Word7"中找到所有单词的顺序不同。 and if sample string is "Word5 Word7 Word3 Word2" then it shouldn't returns. 如果样本字符串是"Word5 Word7 Word3 Word2"则不应返回。

You need anchored look-aheads: 您需要锚定先行:

^(?=.*\bWord1\b)(?=.*\bWord2\b)(?=.*\bWord3\b)

See demo 观看演示

If there are newline symbols in the input string, you need to use an /s modifier. 如果输入字符串中包含换行符,则需要使用/s修饰符。

Here is an IDEONE demo : 这是一个IDEONE演示

$re = '/^(?=.*\bWord1\b)(?=.*\bWord2\b)(?=.*\bWord3\b)/'; 
$str = "Word4 Word2 Word1 Word3 Word5 Word7"; 

$myPregMatch = (preg_match($re, $str));
 if ($myPregMatch){
    echo  "FOUND !!!";
 }

Result: FOUND !!! 结果:发现FOUND !!!

it maybe faster to check every word 检查每个单词可能更快

$string = "Word4 Word2 Word1 Word3 Word5 Word7";  // input string

$what = "Word2 Word1 Word3";                      // words to test
$words = explode(' ', $what);                     // Make array

$i = count($words);
while($i--) 
   if (false == strpos($string, $words[$i])) 
     break;

$result = ($i==-1);   // if $i == -1 all words are present in input string

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

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