Page 1 of 1

regex compilation error

Posted: Fri May 07, 2010 2:39 pm
by scanlin
Hi,

I'm moving code from one server to another and something that used to work no longer works.

On the OLD server, this worked just fine:

$agent="mozilla/5.0 (macintosh; u; intel mac os x 10.5; en-us; rv:1.9.2.3) gecko/20100401 firefox/3.6.3 firephp/0.4";
$pattern = '#(?<browser>msie|firefox|safari|chrome|opera)[/ ]+(?<version>[0-9]+(?:\.[0-9]+)?)#';
if (!preg_match_all($pattern, $agent, $matches))
// do something...

on the NEW server with the same code I get this error:

Warning: preg_match_all() [function.preg-match-all]: Compilation failed: unrecognized character after (?< at offset 3 in [url removed] on line 78

I'm not an expert in regex or php. Any help or pointers greatly appreciated... Thanks!

Re: regex compilation error

Posted: Fri May 07, 2010 3:41 pm
by John Cartwright
It sounds like your PHP version does not support named groups (which groups your matches by name instead of numerical index, but is not neccesary).

Code: Select all

$pattern = '#(?<browser>msie|firefox|safari|chrome|opera)[/ ]+(?<version>[0-9]+(?:\.[0-9]+)?)#';
I would simply remove the <browser> and <version> from the pattern, and adjust the $matches handling accordingly, or upgrade your version of PHP.

Re: regex compilation error

Posted: Fri May 07, 2010 4:39 pm
by ridgerunner
John is correct. The '(?<name>...)' and '(?'name'...)' syntax for named groups was added to PCRE version 7.0. Older versions only support the Python syntax for named groups: '(?P<name>...)'.

Try changing your regex like so:

Code: Select all

$agent="mozilla/5.0 (macintosh; u; intel mac os x 10.5; en-us; rv:1.9.2.3) gecko/20100401 firefox/3.6.3 firephp/0.4";
$pattern = '#(?P<browser>msie|firefox|safari|chrome|opera)[/ ]+(?P<version>[0-9]+(?:\.[0-9]+)?)#';
if (!preg_match_all($pattern, $agent, $matches))
  // do something...
Hope this helps! :)

Re: regex compilation error

Posted: Fri May 07, 2010 5:08 pm
by scanlin
Adding the "P"s did it. Thanks!