0

I noticed someone using preg_replace() with double backslashes to escape, (e.g., <\\/div> instead of <\/div>).

Is this necessary? I tried both ways and I don't see what's the difference.

simple example...

preg_replace('/<div>\\s*text<\\/div>/', '', $somestring);

vs

preg_replace('/<div>\s*text<\/div>/', '', $somestring);

Sunny
  • 2,232
  • 7
  • 24
  • 36
  • Double escape is necessary if you use double quotes for your string (PHP will try to interpret the `\ ` in the string, so you need to escape once for the string, once for the regex). It's useless with single quoted strings (unless you want to use a literal `\ ` in your regex). See [here](http://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php) for the diff. – Robin Apr 22 '14 at 09:00

3 Answers3

1

A backslash in a PHP string literal can have a special meaning. For example "\n" is a newline, not the string "\n". To write the string "\n", you need to escape the backslash as "\\n". However, if the character following the backslash doesn't have any special meaning, the backslash is taken as is. E.g. "\foo" is the string "\foo". In single-quoted strings there's only a single case in which you need to escape the backslash, which is directly before the end of the string: 'foo\\' → "foo\".

So, writing \\/ in a PHP string literal or \/ has the same meaning, because / does not have any special significance to PHP. Either way is correct. This is not about regex syntax but about PHP syntax.

deceze
  • 510,633
  • 85
  • 743
  • 889
0

It's not necessary when you using single quote, it makes no difference in your code example. (For using double quote, it's only necessary when combine with the next char has special meaning)

For single quotes( and so does double quotes), backslash has to be escaped only when it's the last character of the string.

You have to write 'foo\\' instead of 'foo\' or backslash will escape the single quote and leads syntax error.

xdazz
  • 158,678
  • 38
  • 247
  • 274
0

You can simply use:

preg_replace('%<div>\s*text</div>%', '', $somestring);

In this case, you don't need to escape anything.

PHP - Escape sequences
http://www.php.net/manual/en/regexp.reference.escape.php

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • 1
    To match one literal ``\`` in a PHP string literal regex you'll have to escape it a few more times: `'/\\\\/'` – deceze Apr 22 '14 at 09:37