2014-03-27 289 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; 
    } 
    } 
}