开发者

preg_replace escape slashes

开发者 https://www.devze.com 2023-02-05 07:16 出处:网络
I get the unknown m开发者_开发技巧odifier error when the pattern contains slashes code: preg_replace(\'/$v/\', $replacement, $string)

I get the unknown m开发者_开发技巧odifier 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?


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);


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消