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

我想用 \'</ code>替换'</ code>但不是 \'</ code>,因为它们已经被转义。</ p>
</ div>

展开原文

原文

I want to replace ' with \' but not \' since they are already escaped.

du718589
du718589 你能分享一下你尝试过的东西吗?
4 年多之前 回复

1个回答

Pretty simple with lookarounds:

(?<!\\)'

See a demo on regex101.com.
You'll need to escape the backslashes as well for 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

?>

See a demo on ideone.com.

duanlao6573
duanlao6573 小心这个。 \\'即使是反转的反斜杠也不会匹配,而不是报价。
4 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐