Ken Tang Ken Tang - 1 year ago 124
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?


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

Answer Source

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...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download