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