[英]alternative to if(preg_match() and preg_match())
我想知道是否可以替換if(preg_match('/boo/', $anything) and preg_match('/poo/', $anything))
用正則表達式
$anything = 'I contain both boo and poo!!';
例如..
據我對您的問題的了解,您正在尋找一種僅使用一個正則表達式來檢查字符串中是否同時存在“ poo”和“ 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”,那么實際上很難找出正則表達式的問題:是否有AND運算符? 看來您將不得不堅持php測試。
正如其他人在其他答案中指出的那樣,您可以通過更改正則表達式來實現。 但是,如果要改用數組,則不必列出長的正則表達式模式,則可以使用如下代碼:
// 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;
}
}
盡量避免使用正則表達式,因為它們的效率要低得多!
從字面上講條件
if(preg_match('/[bp]oo.*[bp]oo/', $anything))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.