2013-04-29 63 views
2


我想知道,如果我们可以更换if(preg_match('/boo/', $anything) and preg_match('/poo/', $anything))
用正则表达式..
替代,如果(的preg_match()和的preg_match())

$anything = 'I contain both boo and poo!!'; 

例如..

+1

要告诉你实话,这已经是一个正则表达式 – 2013-04-29 14:15:25

+0

@YourCommonSense我的意思只有一个正则表达式 – iguider 2013-04-29 14:47:29

回答

3

从我对你的问题的理解中,你正在寻找一种方法来检查一个字符串中是否存在“poo”和“boo”,只用一个正则表达式。我想不出比这更优雅的方式;

preg_match('/(boo.*poo)|(poo.*boo)/', $anything); 

这是我能想到的,以确保这两个模式的字符串不顾秩序中存在的唯一途径。当然,如果你知道他们总是应该以相同的顺序,这将使它更简单=]

编辑 通过MisterJ在他的回答挂后看完后,它似乎一个更简单的正则表达式可能是;

preg_match('/(?=.*boo)(?=.*poo)/', $anything); 
2

通过使用管道:

if(preg_match('/boo|poo/', $anything)) 
+1

情况下,不足以替代 – 2013-04-29 14:11:56

+1

我认为这将替换:如果(的preg_match(“/ BOO /”,$什么)**或** preg_match('/ poo /',$ anything)) – iguider 2013-04-29 17:47:05

0

你可以通过改变你的正规快递正如其他人在其他答案中指出的那样。但是,如果你想用一个数组代替,所以你不必列出很长的正则表达式,然后用这样的:

// 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; 
    } 
} 

尽量避免正则表达式如果可能的话,因为他们少了很多高效!

+0

为什么downvote?谨慎评论? – 2013-04-29 14:11:51

+0

这不是我谁downvoting任何人..:/ – iguider 2013-04-29 14:43:59

+0

我真的很感激你的答案.. – iguider 2013-04-29 17:45:30

0

要充分条件字面上

if(preg_match('/[bp]oo.*[bp]oo/', $anything)) 
1

您可以使用@sroes提到的逻辑或为:

if(preg_match('/(boo)|(poo)/,$anything))问题还有就是你不知道哪一个匹配。

在这一个,你会匹配“我包含嘘”,“我包含poo”和“我包含boo和poo”。 如果你只想匹配“我包含boo和poo”,这个问题真的很难找出Regular Expressions: Is there an AND operator? ,似乎你将不得不坚持php测试。