Ken Tang Ken Tang - 4 months ago 16
PHP Question

PHP preg_match "AND" operator

I use "OR" operator "|" to match onle of the words of $name variable

$name = "one five six two";
if (preg_match('/(one|two)/i', $name)) {return true;}


What operator should I use with preg_match to have "AND" condition if that words is inside of $name?

i.e.

if (preg_match('/(two "AND" five)/i', $name)) {return true;}

Answer

If you still want to use regex, you'll need positive lookaheads:

if (preg_match('/^(?=.*one)(?=.*two)/i', $name)) {return true;}

It's not recommended for simple stuff (kind of overkill), and it gets messy with more complex stuff...