In PHP do i need to escape backslashes?

后端 未结 6 1017
予麋鹿
予麋鹿 2020-11-30 10:09

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         


        
相关标签:
6条回答
  • 2020-11-30 10:27

    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.

    0 讨论(0)
  • 2020-11-30 10:31

    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.

    0 讨论(0)
  • 2020-11-30 10:33

    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.

    0 讨论(0)
  • 2020-11-30 10:42

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

    0 讨论(0)
  • 2020-11-30 10:43

    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'
    
    0 讨论(0)
  • 2020-11-30 10:51

    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&#92;Models&#92;User';
    

    It will print:

    Application\Models\User

    0 讨论(0)
提交回复
热议问题