Alternative way to write string literals in PHP? (without ' or ")

怎甘沉沦 提交于 2019-12-18 12:22:20

问题


What could I use in PHP in place of the normal ' and " symbols around something?

Example:

echo("Hello, World!")

回答1:


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?


来源:https://stackoverflow.com/questions/10886899/alternative-way-to-write-string-literals-in-php-without-or

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!