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
?>
請注意這一點。即使它是反斜線,而不是引號,'\'將不匹配。 – mcrumley
你能分享你試過嗎? –