Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to find \"

Tags:

regex

php

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?

like image 415
JMC Avatar asked Mar 09 '26 08:03

JMC


2 Answers

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.

like image 169
Floern Avatar answered Mar 10 '26 20:03

Floern


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
'/\"/'             /\"/               "
'/\\"/'            /\"/               "
'/\\\"/'           /\\"/              \"
'/\\\\"/'          /\\"/              \"
'/\\\\\"/'         /\\\"/             \"
'/\\\\\\"/'        /\\\"/             \"
'/\\\\\\\"/'       /\\\\"/            \\"

Bonus backslash

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.

like image 39
mercator Avatar answered Mar 10 '26 21:03

mercator



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!