有没有其他方法可以在PHP中编写字符串文字(不带'或')? [英] Is there an alternative way to write string literals in PHP (without ' or ")?

查看:83
本文介绍了有没有其他方法可以在PHP中编写字符串文字(不带'或')?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在PHP中使用什么代替普通的'和(周围没有(或'或')符号)?

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

示例:

echo("Hello, World!")

推荐答案

封装字符串有4种方法,单引号',双引号"

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

阅读完整的php .net文章.

分隔字符串的第三种方法是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/zh-CN/language.types.string.php#language.types.string.syntax.heredoc

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


Nowdoc

Nowdocs是单引号字符串,heredocs是双引号字符串. nowdoc的指定方式与heredoc相似,但是在nowdoc内不进行任何解析.该结构非常适合嵌入PHP代码或其他大型文本块,而无需进行转义.它具有与SGML构造相同的一些功能,即声明了一个不用于解析的文本块.

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.

用相同的<<<<用于heredocs的序列,但其后的标识符用单引号引起来,例如<<<'EOT'.关于Heredoc标识符的所有规则也适用于nowdoc标识符,尤其是那些与结束标识符的外观有关的规则.

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/zh-CN/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.

如果必须大量添加引号,请使用 addslashes()函数:

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?

这篇关于有没有其他方法可以在PHP中编写字符串文字(不带'或')?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆