messy
messy

Reputation: 915

Regex for escaping single quotes which are not already escaped

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

Upvotes: 3

Views: 868

Answers (1)

Jan
Jan

Reputation: 43199

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.

Upvotes: 2

Related Questions