2013-04-29 60 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測試。