正则表达式用于转义尚未转义的单引号

时间:2016-04-18 13:12:11

标签: php regex

我想将'替换为\',而不是\',因为它们已被转义。

1 个答案:

答案 0 :(得分:2)

使用 lookarounds 非常简单:

(?<!\\)'

请参阅a demo on regex101.com 您还需要为PHP

转义反斜杠
<?php
$string = "I want to replace ' with \' but not \' since they are already escaped";
$regex = "~(?<!\\\)'~";

echo preg_replace($regex, "\\'", $string);
# Output: I want to replace \' with \' but not \' since they are already escaped

?>

参见 a demo on ideone.com