What's the regular expression to find \"
I think it's this: '/\\"/' but I need to use it on a really large dataset so need to make sure this is correct.
I need to replace it with " so my code is : $data = preg_replace('/\\"/', '"', $data)
Is that correct?
For matching backslashes you need to 'double-escape' them, so you have four \ at the end:
$data = preg_replace('/\\\\"/', '"', $data);
Why you need 4 \: PHP parses a string \\" as \" and RegEx interprets this as " since in RegEx you don't need to escape ". So it wont match \". \\\\" will be parsed as \\" which will be interpreted as \" by RegEx.
A backslash does not need to be escaped in either a single-quoted string or a regular expression, unless the following character is a character that can be escaped (such as the backslash itself).
A double quote does not need to be escaped and cannot be escaped in a single-quoted string. In a regular expression it doesn't have to be either, but it can be.
That means \\ in both a single-quoted string and a regular expression becomes \, while \" in a single-quoted string remains \", while in a regular expression it becomes ".
However, in PHP you can only create a regular expression from a string, so you have to escape twice.
In other words...
Original string String processed Regexp processed
'/\"/' /\"/ "
'/\\"/' /\"/ "
'/\\\"/' /\\"/ \"
'/\\\\"/' /\\"/ \"
'/\\\\\"/' /\\\"/ \"
'/\\\\\\"/' /\\\"/ \"
'/\\\\\\\"/' /\\\\"/ \\"
In a double-quoted string, of course, the " does need to be escaped, so...
"/\"/" /"/ "
"/\\"/" syntax error
"/\\\"/" /\"/ "
"/\\\\"/" syntax error
"/\\\\\"/" /\\"/ \"
"/\\\\\\"/" syntax error
"/\\\\\\\"/" /\\\"/ \"
"/\\\\\\\\"/" syntax error
"/\\\\\\\\\"/" /\\\\"/ \\"
I think you should probably go for preg_replace("/\\\\\\\"/", "\"", $data) just to be on the safeconfusing side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With