Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP preg_match "AND" operator

I use the "OR" operator "|" to match one of the words of the $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 an "AND" condition if those words are inside of $name?

For example,

if (preg_match('/(two "AND" five)/i', $name)) {return true;}
like image 877
Ken Tang Avatar asked Sep 12 '25 23:09

Ken Tang


1 Answers

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

like image 79
Jerry Avatar answered Sep 15 '25 13:09

Jerry