问题
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;}
回答1:
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...
回答2:
I think you just need to separate two conditions and use &&
as follow
if(preg_match('/(two)/i', $name) && preg_match('/(five)/i', $name)) {return true;}
Learn more here
回答3:
You might just do this without resorting to regular expressions:
if (strpos($name, 'one') !== false && strpos($name, 'two') !== false) {
// do something
}
回答4:
if ( preg_match('/two/i', $name) && preg_match('/five/i', $name) ) {return true;}
回答5:
Don't use preg_match
if you only match one word. Regular expression use more computer resources compared to strpos
.
Do not use preg_match()
if you only want to check if one string is contained in another string. Use strpos()
or strstr()
instead as they will be faster. (PHP.net).
if (str_pos($name, 'two') !== false
&& str_pos($name, 'five') !== false) {
return true;
}
来源:https://stackoverflow.com/questions/22222574/php-preg-match-and-operator