3

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;
          }
        }
     }
Amy
  • 59
  • 2
  • 5

3 Answers3

6

$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
h2ooooooo
  • 39,111
  • 8
  • 68
  • 102
3

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;
     }
   }
}
kero
  • 10,647
  • 5
  • 41
  • 51
0

You need preg_quote():

preg_match("/".preg_quote($item)."/", $opText)
xdazz
  • 158,678
  • 38
  • 247
  • 274