Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to escape backslashes in PHP?

Do I need to escape backslash in PHP?

echo 'Application\Models\User'; # Prints "Application\Models\User"
echo 'Application\\Models\\User'; # Same output
echo 'Application\Model\'User'; # Gives "Application\Model'User"

So it's an escape character. Shouldn't I need to escape it (\) if I want to refer to Application\Models\User?

like image 891
Jiew Meng Avatar asked Aug 05 '10 14:08

Jiew Meng


People also ask

How do you escape a backslash in PHP?

In PHP, an escape sequence starts with a backslash \ . Escape sequences apply to double-quoted strings. A single-quoted string only uses the escape sequences for a single quote or a backslash.

What does it mean to escape backslashes in R?

In R (and elsewhere), the backslash is the “escape” symbol, which is followed by another symbol to indicate a special character. For example, "\t" represents a “tab” and "\n" is the symbol for a new line (hard return).

What does backslash mean in PHP?

\ (backslash) is the namespace separator in PHP 5.3. A \ before the beginning of a function represents the Global Namespace. Putting it there will ensure that the function called is from the global namespace, even if there is a function by the same name in the current namespace.


3 Answers

In single quoted strings only the escape sequences \\ and \' are recognized; any other occurrence of \ is interpreted as a plain character.

So since \M and \U are no valid escape sequences, they are interpreted as they are.

like image 188
Gumbo Avatar answered Oct 11 '22 18:10

Gumbo


In single quoted strings, it's optional to escape the backslash, the only exception is when it's before a single quote or a backslash (because \' and \\ are escape sequences).

This is common when writing regular expressions, because they tend to contain backslashes. It's easier to read preg_replace('/\w\b/', ' ', $str) than /\\w\\b/.

See the manual.

like image 33
Artefacto Avatar answered Oct 11 '22 17:10

Artefacto


Since your last example contains a quote ('), you need to escape such strings with the addslashes function or simply adding a slash yourself before it like this:

'Application\Model\\'User'
like image 22
Sarfraz Avatar answered Oct 11 '22 19:10

Sarfraz