Is there an alternative way to write string literals in PHP (without ' or ")?

后端 未结 1 1690
梦谈多话
梦谈多话 2020-12-31 08:21

What could I use in PHP in place of the normal \' and (without \' or \") symbols around something?

Example:

echo(\"Hello, World!\")


        
相关标签:
1条回答
  • 2020-12-31 08:50

    There are 4 ways to encapsulate strings, single quotes ', double quotes ", heredoc and nowdoc.

    Read the full php.net article here.

    Heredoc

    A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.

    http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

    $str = <<<EOD
    Example of string
    spanning multiple lines
    using heredoc syntax.
    EOD;
    

    Nowdoc

    Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML construct, in that it declares a block of text which is not for parsing.

    A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.

    http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc

    $str = <<<'EOD'
    Example of string
    spanning multiple lines
    using nowdoc syntax.
    EOD;
    

    Escaping

    If you want to use literal single or double quotes within single or double quoted strings, you have to escape them:

    $str = '\''; // single quote
    $str = "\""; // double quote
    

    As Herbert noted, you don't have to escape single quotes within a double quoted strings and you don't have to escape double quotes within a single quoted string.


    If you have to add quotes on a large scale, use the addslashes() function:

    $str = "Is your name O'reilly?";
    echo addslashes($str); // Is your name O\'reilly?
    
    0 讨论(0)
提交回复
热议问题