Search code examples
phpserver-sidepreg-match-allregex-negation

Issue with preg_match_all : Compilation failed unmatched parentheses


I'm facing following warning

preg_match_all(): Compilation failed: unmatched parentheses at offset 4

when used preg_match_all

following is the code

preg_match_all('/' . $word . '/i', $text, $matches);

Solution

  • Looks like there are some special characters on $word used in the regular expression syntax. Your $word contains one of the following characters: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : - #. You have to quote these characters using preg_quote:

    preg_match_all('/'.preg_quote($word).'/i', $text, $matches);