PREG_MATCH 检查所有单词和条件
PREG_MATCH check all words and condition
我写了一个正则表达式,它在 OR 条件下搜索搜索词,这样只要三个单词在字符串中出现,而不管它们的顺序如何。现在我只想放置一个 AND 条件,因为我想以不同的顺序在字符串中同时获取所有三个单词。
这是我的 preg_match()
正则表达式。
$myPregMatch = (preg_match("/\b^(Word1|Word2|Word3)\b/", "Word4 Word2 Word1 Word3 Word5 Word7"));
if ($myPregMatch){
echo "FOUND !!!";
}
我想在字符串 "Word4 Word2 Word1 Word3 Word5 Word7"
中找到所有单词都以不同的顺序出现。如果样本字符串是 "Word5 Word7 Word3 Word2"
那么它不应该是 returns.
您需要锚定的前瞻:
^(?=.*\bWord1\b)(?=.*\bWord2\b)(?=.*\bWord3\b)
见demo
如果输入字符串中有换行符,需要使用/s
修饰符。
这是一个 IDEONE demo:
$re = '/^(?=.*\bWord1\b)(?=.*\bWord2\b)(?=.*\bWord3\b)/';
$str = "Word4 Word2 Word1 Word3 Word5 Word7";
$myPregMatch = (preg_match($re, $str));
if ($myPregMatch){
echo "FOUND !!!";
}
结果:FOUND !!!
检查每个单词可能会更快
$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
我写了一个正则表达式,它在 OR 条件下搜索搜索词,这样只要三个单词在字符串中出现,而不管它们的顺序如何。现在我只想放置一个 AND 条件,因为我想以不同的顺序在字符串中同时获取所有三个单词。
这是我的 preg_match()
正则表达式。
$myPregMatch = (preg_match("/\b^(Word1|Word2|Word3)\b/", "Word4 Word2 Word1 Word3 Word5 Word7"));
if ($myPregMatch){
echo "FOUND !!!";
}
我想在字符串 "Word4 Word2 Word1 Word3 Word5 Word7"
中找到所有单词都以不同的顺序出现。如果样本字符串是 "Word5 Word7 Word3 Word2"
那么它不应该是 returns.
您需要锚定的前瞻:
^(?=.*\bWord1\b)(?=.*\bWord2\b)(?=.*\bWord3\b)
见demo
如果输入字符串中有换行符,需要使用/s
修饰符。
这是一个 IDEONE demo:
$re = '/^(?=.*\bWord1\b)(?=.*\bWord2\b)(?=.*\bWord3\b)/';
$str = "Word4 Word2 Word1 Word3 Word5 Word7";
$myPregMatch = (preg_match($re, $str));
if ($myPregMatch){
echo "FOUND !!!";
}
结果:FOUND !!!
检查每个单词可能会更快
$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