PHP and backslashes in strings

2019-05-01 11:19发布

问题:

Can anyone tell me what is happening here?

<?php
// true
var_dump('\\ ' === '\ ');

// false
var_dump('\\\\ ' === '\\ ');

// true
var_dump('\\\\ ' === '\\\ ');

回答1:

\ inside a string literal introduces several types of escape sequences, \\ is the escape sequence for a literal "\". But, \s that don't resolve to an escape sequence are also taken as literal "\".

Therefor, '\\ ' stands for the string "\ ", '\\\\ ' stands for the string "\\ ", just as '\\\ '. Try:

echo '\\\\ ';   -> \\ 

See http://php.net/manual/en/language.types.string.php#language.types.string.syntax.single.



回答2:

In single quoted strings, no escape sequences are interpolated. A backslash is only an escape character if it immediately precedes a single quote, or a backslash.

So:

var_dump('\\ '); // String (2) "\ "
var_dump('\ '); // String (2) "\ "
// They do match

var_dump('\\\\ '); // String (3) "\\ "
var_dump('\\ '); // String (2) "\ "
// They don't match

var_dump('\\\\ '); // String (3) "\\ "
var_dump('\\\ '); // String (3) "\\ "
// They do match

This is expected and documented behaviour, although it can be difficult to wrap you head around on the face of it.



回答3:

In 1st example you're comparing

"\ " and "\ " which is TRUE

in 2nd

"\\ " and "\ " which is FALSE

in 3rd

"\\ " and "\\ " which is TRUE

If you print out your strings

$s = array('\ ', '\\ ', '\\\ ', '\\\\ ');
var_dump($s);

you'll get

array(4) {
  [0]=>
  string(2) "\ "
  [1]=>
  string(2) "\ "
  [2]=>
  string(3) "\\ "
  [3]=>
  string(3) "\\ "
}

All double-slashes '\\' have been converted into single-slashes '\' and sigle-slashes remain the same. Escaping works the same way inside single and double-quoted strings.