Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_match(): Unknown modifier 'h' in php

Tags:

php

This error is shown when trying to match an array of words to a user typed text..

     foreach($items as $k=>$item){
        if($item!='' && preg_match("/".$item."/", $opText)){
          if(!in_array($item,$params[$val['name']],true)){
             $params[$val['name']][]=$item;
          }
        }
     }
like image 833
Amy Avatar asked Oct 14 '25 08:10

Amy


2 Answers

$item has a / in it, which means that it thinks that the regex ends sooner than it does.

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

You can use the preg_quote($string, '/') function for this to turn it into the following:

/goldfish\/herring/
//       ^ Escaped

Usage:

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

Tip:

If this is a hardcoded regex, you can change your escape character to make the regex easier to read by not having to escape a commonly used character:

~goldfish/herring~
//       ^       ^
//       |       \- Using a different modifier
//       |       
//       \- Different from the modifier, so we don't have to escape it
like image 128
h2ooooooo Avatar answered Oct 16 '25 23:10

h2ooooooo


If you have dynamic input, it would be wise to use preg_quote() to be sure that this input doesn't violate any regular expression rules.

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;
     }
   }
}
like image 24
kero Avatar answered Oct 16 '25 23:10

kero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!