【问题标题】:preg_match(): Unknown modifier 'h' in phppreg_match():php 中的未知修饰符“h”
【发布时间】:2014-05-06 05:25:30
【问题描述】:

在尝试将单词数组与用户键入的文本匹配时显示此错误..

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

【问题讨论】:

  • 很可能$item 包含一个/,后跟一个h

标签: php


【解决方案1】:

$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;
      }
    }
 }

提示

如果这是一个硬编码的正则表达式,您可以更改转义字符,使正则表达式更易于阅读,而不必转义常用字符:

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

【讨论】:

    【解决方案2】:

    你需要preg_quote():

    preg_match("/".preg_quote($item)."/", $opText)
    

    【讨论】:

      【解决方案3】:

      如果您有动态输入,明智的做法是使用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;
           }
         }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-24
        • 1970-01-01
        • 1970-01-01
        • 2011-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多