Zebra
Zebra

Reputation: 4006

preg_replace escape slashes

I get the unknown modifier error when the pattern contains slashes

code:

preg_replace('/$v/', $replacement, $string)


var $v, sometimes a directory path.

$v = folder/folder/file.ext



How do I deal with the $v in preg_replace?

Upvotes: 2

Views: 12823

Answers (3)

Alix Axel
Alix Axel

Reputation: 154513

None of the existing answers is absolutely right.

The correct way to escape PREG symbols with preg_replace() is the following:

$delim = '~';
$search = preg_quote('folder/folder/file.ext', $delim);
$replace = addcslashes($replace, '\\$');
//$replace = preg_quote($replace); // don't use $delim here!

$string = preg_replace($delim . $search . $delim, $replace, $string);

$replace also needs to be escaped, otherwise $0 would return the matched string for example.

Upvotes: 3

BoltClock
BoltClock

Reputation: 723438

Rolled back to my original answer since that's what turned out to work and dany accepted my answer.

Escape it with preg_quote(), and use double quotes when placing it in a string:

$v = preg_quote($v, '/');
echo preg_replace("/$v/", $replacement, $string);

Then again if your $v doesn't have any regex metacharacters, and you just want to do an exact match, use str_replace() instead:

echo str_replace($v, $replacement, $string);

Upvotes: 5

mario
mario

Reputation: 145482

The correct way to escape strings for use in regular expressions is preg_quote():

$v = preg_quote($v, '/');
preg_replace('/$v/', $replacement, $string)

It takes care that not only the delimiter / gets escaped, but also all other regex meta characters like dots or braces or other escape sequences.

Upvotes: 0

Related Questions