After having some trouble building a json
string I discovered some text in my database containing double quotes. I need to replace the quotes with their escaped equivalents. This works:
function escape( $str ) {
return preg_replace('/"/',"\\\"",$str);
}
but it doesn't take into account that a quote may already be escaped. How can I modify the expression so that it's only true only for a non escaped character?
You need to use a negative lookbehind here
function escape( $str ) {
return preg_replace('/(?<!\\)"/',"\\\"",$str);
}
Try first remove the '\' from all escaped doube-quotes, than escape all double-quotes.
str_replace(array('\"', '"'), array('"', '\"'), $str);
Try preg_replace('/([^\\\])"/', '$1\\"', $str);
I believe this will work
regex:
(?<!\\)((?:\\\\)*)"
code:
$re = '/(?<!\\\\)((?:\\\\\\\\)*)"/';
preg_replace($re, '$1\\"', 'foo"bar'); // foo\"bar -- slash added
preg_replace($re, '$1\\"', 'foo\\"bar'); // foo\"bar -- already escaped, nothing added
preg_replace($re, '$1\\"', 'foo\\\\"bar'); // foo\\\"bar -- not escaped, extra slash added