PHP preg_match “AND” operator

混江龙づ霸主 提交于 2019-12-11 02:53:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!