regex compilation error

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
scanlin
Forum Newbie
Posts: 2
Joined: Fri May 07, 2010 2:34 pm

regex compilation error

Post 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!
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: regex compilation error

Post 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.
User avatar
ridgerunner
Forum Contributor
Posts: 214
Joined: Sun Jul 05, 2009 10:39 pm
Location: SLC, UT

Re: regex compilation error

Post 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! :)
scanlin
Forum Newbie
Posts: 2
Joined: Fri May 07, 2010 2:34 pm

Re: regex compilation error

Post by scanlin »

Adding the "P"s did it. Thanks!
Post Reply