1

I have two string variables which are both file paths. The code that worked used ereg which is deprecated, so I'm trying to rewrite it using preg_match:

Old code that worked:

$path1 = quotemeta($path);
ereg("$path1(.*)$", $path2, $matches);

Using preg_match which doesn't seem to work:

$path1 = quotemeta($path);
preg_match("/$path1(.*)$/", $path2, $matches);

It gives

preg_match(): Unknown modifier 'V' error.

Also, the main thing I'm trying to obtain is $matches[1], which is the text that matched the first captured parenthesized subpattern, so I'm thinking I can't really use substr().

hakre
  • 193,403
  • 52
  • 435
  • 836
highlightall
  • 109
  • 1
  • 2
  • 9

2 Answers2

1

If there are some special-characters in your $path variable, those should be escaped -- and they should be escaped considering you are using PCRE ; and not POSIX-regex.


This can be done using the preg_quote function ; which means your code would look like this :

$path1 = preg_quote($path, '/');
preg_match("/$path1(.*)$/", $path2, $matches);

In particular, note that PCRE use a delimiter arround the regex -- here, you used a / ; this delimiter has to be passed to preg_quote, as this function doesn't, by default, escape the / character.


The quotemeta function you were using doesn't quote all the characters that are used by PCRE.

As you are porting some code from POSIX-regex to PCRE, you should take a look at the PCRE Patterns section of the manual : PCRE are very powerful, but that power comes with a couple of tricks...

Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
0

You can solve this one without regular expressions:

$pos = strpos($path2, $path);
if ($pos !== false) {
    $match = substr($path2, $pos+strlen($path));
}
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • I think $match gives me the matched string instead of text that matched the parenthesized subpattern. But this is definitely working code. Thanks. – highlightall Mar 04 '10 at 21:02
  • @highlightall: Put `$path` in front of it and you have the full match. – Gumbo Mar 04 '10 at 21:15