Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP and backslashes in strings

Can anyone tell me what is happening here?

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

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

// true
var_dump('\\\\ ' === '\\\ ');
like image 256
Dalibor Karlović Avatar asked Mar 28 '12 12:03

Dalibor Karlović


People also ask

How remove forward and backward slash from string in PHP?

The stripslashes() function removes backslashes added by the addslashes() function. Tip: This function can be used to clean up data retrieved from a database or from an HTML form.

What does ?: Mean in PHP?

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.

Is backslash a string?

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.

What is Heredoc and Nowdoc in PHP?

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping.


2 Answers

\ 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.

like image 107
deceze Avatar answered Oct 10 '22 08:10

deceze


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.

like image 36
DaveRandom Avatar answered Oct 10 '22 09:10

DaveRandom