2014-03-27 297 views
0

試圖匹配單詞的數組用戶鍵入的文本時,將顯示此錯誤未知的修飾詞「H」 ..的preg_match():在PHP

 foreach($items as $k=>$item){ 
     if($item!='' && preg_match("/".$item."/", $opText)){ 
      if(!in_array($item,$params[$val['name']],true)){ 
      $params[$val['name']][]=$item; 
      } 
     } 
    } 
+0

最有可能'$ item'包含了'/'然後是'h'。 –

回答

2

$item中有一個/,這意味着它認爲,正則表達式結束早於它。

/goldfish/herring/ 
//  ^Not actually a modifier (h) - just an unescaped string 

可以使用preg_quote($string, '/')功能即可關閉此爲以下:

/goldfish\/herring/ 
//  ^Escaped 

使用

foreach($items as $k=>$item){ 
    if($item!='' && preg_match("/".preg_quote($item,"/")."/", $opText)){ 
     if(!in_array($item,$params[$val['name']],true)){ 
     $params[$val['name']][]=$item; 
     } 
    } 
} 

提示

我F該是硬編碼的正則表達式,你可以改變你的轉義字符,使正則表達式更容易不必逃避常用字符閱讀:

~goldfish/herring~ 
//  ^ ^
//  |  \- Using a different modifier 
//  |  
//  \- Different from the modifier, so we don't have to escape it 
2

如果你有動態輸入,這將是明智的要使用preg_quote()來確保此輸入不違反任何正則表達式規則。

foreach($items as $k=>$item){ 
    if($item!='' && preg_match("/".preg_quote($item, '/')."/", $opText)){ 
    if(!in_array($item,$params[$val['name']],true)){ 
     $params[$val['name']][]=$item; 
    } 
    } 
}