2016-04-18 78 views

回答

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

+1

請注意這一點。即使它是反斜線,而不是引號,'\'將不匹配。 – mcrumley