开发者

How can I match ALL terms using Regular Expressions in PHP?

I figured out h开发者_开发百科ow to check an OR case, preg_match( "/(word1|word2|word3)/i", $string );. What I can't figure out is how to match an AND case. I want to check that the string contains ALL the terms (case-insensitive).


It's possible to do an AND match in a single regex using lookahead, eg.:

preg_match('/^(?=.*word1)(?=.*word2)(?=.*word3)/i', $string)

however, it's probably clearer and maybe faster to just do it outside regex:

preg_match('/word1/i', $string) && preg_match('/word2/i', $string) && preg_match('/word3/i', $string)

or, if your target strings are as simple as word1:

stripos($string, 'word1')!==FALSE && stripos($string, 'word2')!==FALSE && stripos($string, 'word3')!==FALSE


I am thinking about a situation in your question that may cause some problem using and case:

this is the situation

words = "abcd","cdef","efgh"

does have to match in the string:

string = "abcdefgh"

maybe you should not using REG.EXP


If you know the order that the terms will appear in, you could use something like the following:

preg_match("/(word1).*(word2).*(word3)/i", $string);

If the order of terms isn't defined, you will probably be best using 3 separate expressions and checking that they all matched. A single expression is possible but likely complicated.


preg_match( "/word1.*word2.*word3)/i");

This works but they must appear in the stated order, you could of course alternate preg_match("/(word1.*word2.*word3|word1.*word3.*word2|word2.*word3.*word1| word2.*word1.*word3|word3.*word2.*word1|word3.*word1.*word2)/i");

But thats pretty herendous and you'd have to be crazy!, would be nicer to just use strpos($haystack,$needle); in a loop, or multiple regex matches.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜