我想将'
替换为\'
,而不是\'
,因为它们已被转义。
答案 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 。