2014-10-30 168 views
2

嗨我必須在一個字符串中搜索兩個字符串。 例如如何在一個字符串中搜索兩個字符串?

$string = "The quick brown fox jumped over a lazy cat"; 
if($string contains both brown and lazy){ 
    then execute my code 
} 

我試圖pregmatch這樣,

if(preg_match("/(brown|lazy)/i", $string)){ 
    execute my code 
} 

但是它進入如果如果它們中的一個存在於串中循環。但是我希望它只在兩個字符串出現在父字符串中時才輸入if條件。我怎樣才能做到這一點。

注意:我不想在字符串上循環。 (就像使用strposexplode字符串和foreach分解的陣列上和搜索)

+0

'$ string contains the brown and lazy'這裏的關鍵字是:'和'。 – Shomz 2014-10-30 05:21:47

+0

'$ regex =「/(brown)[^。] *(懶惰)/ i」;'要短得多。 – 2014-10-30 05:24:41

+0

如果你正在尋找一種方法來處理正則表達式,這篇文章解釋瞭如何用正則表達式獲得'和'效果:http://stackoverflow.com/questions/469913/regular-expressions-is-there -an-and-operator – Tim 2014-10-30 05:24:44

回答

5

嘗試像

if(preg_match("/(brown)/i", $string) && preg_match("/(lazy)/i", $string)){ 
    execute my code 
} 

勇也可以嘗試用strpos

if(strpos($string, 'brown') >= 0 && strpos($string, 'lazy') >= 0){ 
    execute my code 
} 
+0

您的strpos示例都是錯誤的:如果位置爲0(字符串的開頭),它將永遠不會返回TRUE,並且'> 0'將失敗。 – Shomz 2014-10-30 05:25:39

+0

對不起,回滾。它會''0' – Gautam3164 2014-10-30 05:25:41

+0

@Shomz是的我也來了解這一點。感謝 – Gautam3164 2014-10-30 05:26:19

3

遲到的回答,如果你希望測試兩個詞的完全匹配:

$regex= "/\b(brown)\b[^.]*\b(lazy)\b/i"; 

$string = "The quick brown fox jumped over a lazy cat"; 

if(preg_match($regex, $string)) 

{ 
    echo 'True'; 
} else { 
    echo 'False'; 
} 

  • 或者,用$regex = "/(brown)[^.]*(lazy)/i";取代它,如果你不想要測試精確匹配,這是一個更短的方法。
+1

謝謝@Fred -ii-爲您的關注:) – 2014-10-30 05:59:22

+1

@BlankHead不客氣。我當時正在測試,並在此過程中離開此頁面,這解釋了我遲到的答案。如果這是你的+1,謝謝:) – 2014-10-30 06:01:07

+0

嘿。請不要提及。 :) – 2014-10-30 06:39:53