views:

98

answers:

2

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().

Any help would be greatly appreciated.

+1  A: 

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
Wow that totally fixed it! Thanks for making my day!
highlightall
You're welcome :-) Have fun !
Pascal MARTIN
A: 

You can solve this one without regular expressions:

$pos = strpos($path2, $path);
if ($pos !== false) {
    $match = substr($path2, $pos+strlen($path));
}
Gumbo
I think $match gives me the matched string instead of text that matched the parenthesized subpattern. But this is definitely working code. Thanks.
highlightall
@highlightall: Put `$path` in front of it and you have the full match.
Gumbo