Jiew Meng
Jiew Meng

Reputation: 88187

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?

Upvotes: 20

Views: 65728

Answers (6)

bizna
bizna

Reputation: 712

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\Models\User';

It will print:

Application\Models\User

Reference:

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382626

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'

Upvotes: 1

Artefacto
Artefacto

Reputation: 97805

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.

Upvotes: 2

Martin Bean
Martin Bean

Reputation: 39389

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.

Upvotes: 0

Hollance
Hollance

Reputation: 2966

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

Upvotes: -1

Gumbo
Gumbo

Reputation: 655129

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.

Upvotes: 35

Related Questions