Ken Tang Ken Tang - 8 months ago 39
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;}


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