我想知道我们是否可以更换if(preg_match('/boo/', $anything) and preg_match('/poo/', $anything))
使用正则表达式
$anything = 'I contain both boo and poo!!';
例如。。
根据我对您问题的理解,您正在寻找一种方法,只使用一个正则表达式来检查字符串中是否同时存在"poo"one_answers"boo"。我想不出比这更优雅的方式了;
preg_match('/(boo.*poo)|(poo.*boo)/', $anything);
这是我能想到的确保两种模式都存在于字符串中的唯一方法,而不考虑顺序。当然,如果你知道它们总是按照相同的顺序排列,那就更简单了=]
编辑在阅读了MisterJ在他的回答中链接到的帖子后,似乎可以找到一个更简单的正则表达式;
preg_match('/(?=.*boo)(?=.*poo)/', $anything);
通过使用管道:
if(preg_match('/boo|poo/', $anything))
您可以使用@sroes:提到的逻辑或
if(preg_match('/(boo)|(poo)/,$anything))
问题是你不知道哪一个匹配。
在这个例子中,你将匹配"我含有boo"、"我含有poo"one_answers"我含有boo和poo"。如果你只想匹配"I contained boo and poo",那么问题真的很难弄清楚正则表达式:有and运算符吗?而且您似乎必须坚持php测试。
采用条件字面
if(preg_match('/[bp]oo.*[bp]oo/', $anything))
正如其他人在其他答案中指出的那样,您可以通过更改正则表达式来实现这一点。但是,如果您想使用数组,这样您就不必列出一个长的正则表达式模式,那么可以使用以下内容:
// Default matches to false
$matches = false;
// Set the pattern array
$pattern_array = array('boo','poo');
// Loop through the patterns to match
foreach($pattern_array as $pattern){
// Test if the string is matched
if(preg_match('/'.$pattern.'/', $anything)){
// Set matches to true
$matches = true;
}
}
// Proceed if matches is true
if($matches){
// Do your stuff here
}
或者,如果你只是试图匹配字符串,那么如果你像这样使用strpos
,效率会高得多:
// Default matches to false
$matches = false;
// Set the strings to match
$strings_to_match = array('boo','poo');
foreach($strings_to_match as $string){
if(strpos($anything, $string) !== false)){
// Set matches to true
$matches = true;
}
}
尽量避免使用正则表达式,因为它们的效率要低得多