I’d like to use a kind of logical operator “AND” in my regular expression.
I tried this:
(?=exp1)(?=exp2)
But in PHP ?= doesn’t work and need to write my program in PHP language. Is there another method? The expression has to match if there are present all the conditions and in any order.
I don’t wanna write every permutation like:
(exp1)(exp2)(exp3)|(exp1)(exp3)(exp2)|....
PHP does support lookahead expressions. You’re probably not using them correctly, though.
Assuming you want to match a string that contains all three of
foo,barandbaz, you need the regexThis will return a match for the strings
foobarbazorbarbazfooetc. However, that match will be the empty string (because the lookaheads don’t consume any characters). If you want the regex to return the string itself, usewhich will then match the entire string if it fulfills all three criteria.
I would simply use
Take note that this will also match a string like
foonly bartender bazooka. If you don’t want that (only allowing pure permutations of one each of the three expressions), you can do it with a little trick:matches
foobarbaz,foobazbar,barfoobaz,barbazfoo,bazfoobarandbazbarfoo(and nothing else). The “trick” is inspired by Jan Goyvaerts’ and Steven Levithan’s excellent book “Regular Expressions Cookbook” (p. 304). It works as follows:fooetc.) is followed by an empty capturing group()which always matches if the required part has been matched.foobarbar, the part(?:foo()|bar()|baz()){3}will have matched, but\3fails, so the overall regex fails.\1\2\3succeeds in matching at the end of the string because each of the capturing groups contains nothing but the empty string.