I think this may be a stupid question, but I am quite confused whether I need to escape backslash in PHP.
echo \'Application\\Models\\User\'; prints Applicat
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.
I think it depends on the context, but it is a good idea to escape backslashes if using it in file paths.
Another good idea is to assign the directory separator to a constant, which I've seen done in various applications before, and use it as thus:
<?php
define('DIRECTORY_SEPARATOR', '\\');
echo 'Application'.DIRECTORY_SEPARATOR . 'Models' . DIRECTORY_SEPARATOR . 'User';
?>
If you wish to save space and typing, others use DS
for the constant name.
<?php
define('DS', '\\');
echo 'Application'.DS.'Models'.DS.'User';
?>
This keeps your application portable if you move from a Windows environment to a *nix environment, as you can simple change the directory separator constant to a forward slash.
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.
You will find the complete explanation here: http://nl.php.net/manual/en/language.types.string.php
Since your last example contains a quote ('
), you need to escape such strings with addslashes function or simply adding a slash yourself before it like this:
'Application\Model\\'User'
If it is to be used in an HTML page, then you might as well use code \ to represent a backslash, like so:
echo 'Application\Models\User';
It will print:
Application\Models\User