18

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jiew Meng
  • 84,767
  • 185
  • 495
  • 805

6 Answers6

33

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.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • But escaping the backslash itself seems to be optional, right? So I can write both `'Hello \world'` and `'Hello \\world'`. Your answer implies that, of course, because `\w` is not a valid escape sequence and thus output as written. – caw Dec 03 '16 at 03:54
  • @caw: No. It does work here, but that's _not_ because escaping the backslash is "optional", but because the the `\w` combination fails to match anything, and therefore falls back to its literal form. But try printing a single `\\`, for example, without escaping. Or anything that ends with a single backslash. You'll get a parse error. – Sz. Jan 24 '18 at 19:24
  • @Sz That is just because the single backslash will then be interpreted as the escape character for the following single quote. You are right, of course. Escaping of the backslash is usually optional for the reason that you stated, namely that it will be an invalid escape sequence in most other cases and thus be printed as a literal backslash. – caw Jan 24 '18 at 21:25
  • @caw, yes, and the goal of my comment was just to prevent some readers of this page from leaving with the wrong idea, and later recalling maybe the simple message, but not the exact subtleties (exceptions) --> a perfect way to create sneaky bugs on long nights (talkin' of backslashes, perhaps in a high-risk filesystem-level code of a later PHP subsystem of Windows :) ). – Sz. Jan 25 '18 at 10:35
2

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.

Artefacto
  • 96,375
  • 17
  • 202
  • 225
  • 2
    Backslashes do have to be escaped, as stated in the manual and the accepted answer. – Gras Double Jun 22 '13 at 00:22
  • @GrasDouble No, they don't. This answer is correct. – caw Dec 03 '16 at 03:56
  • 2
    In practice they don't have to be escaped, except for one case: if the backslash is the last character. `'foo\\'` works, but `'foo\'` doesn't. I think the non-escaped backslashes should be considered as a syntactic sugar. For consistency you may want to always escape them, but it's up to you. – Gras Double Dec 03 '16 at 05:14
  • @GrasDouble: "escaped, except for one case", well, no. :) Artefacto was right in that particular point (only) that it also needs to be escaped before a single quote. – Sz. Jan 24 '18 at 19:36
  • So, to recap: it's _not_ optional, and the answer is therefore not correct. We are just basically "lucky" most of the time. And the exception mentioned in the answer ("before a single quote") is not even the only one, as @GrasDouble revealed correctly. – Sz. Jan 24 '18 at 19:44
  • @Sz. there's no "luck" involved. No one's flipping a coin everytime you write an unescaped backslash. The answer was not correct in that it omitted the one other case when the escaping is necessary. – Artefacto Jan 24 '18 at 19:48
  • Artefacto, unfortunately still not quite correct, after adding the double backslash case. See @GrasDouble's comment here, or mine under the accepted answer. One can still get a parse error following your answer with this wrong idea of escaping backslashes being "optional". (Also notice the quotes around the word "lucky" in my prev. comment. ;) ) – Sz. Jan 24 '18 at 19:50
  • @Sz. The case GrasDouble mentions is the one where a backslash comes before a `'`. To be clear, I'm not saying the `'` must be part of the string's contents. – Artefacto Jan 24 '18 at 19:54
  • Well, nice try, but *still* wrong... :) There are other ways to terminate a string than a single quote. – Sz. Jan 24 '18 at 19:57
  • @Sz. We're talking about single quoted strings here (which is what the question uses). Such strings can only be terminated by an unescaped single quote. – Artefacto Jan 24 '18 at 20:03
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/163856/discussion-between-sz-and-artefacto). – Sz. Jan 25 '18 at 10:02
1

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'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
0

You will find the complete explanation here: http://nl.php.net/manual/en/language.types.string.php

Hollance
  • 2,958
  • 16
  • 15
0

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.

Martin Bean
  • 38,379
  • 25
  • 128
  • 201
0

If it is to be used in an HTML page, then you might as well use HTML character code \ to represent a backslash, like so:

echo 'Application&#92;Models&#92;User';

It will print:

Application\Models\User

Reference:

bizna
  • 702
  • 8
  • 23