当我使用双引号时,为什么 PHP 中的 printf() 不起作用?
printf("by %1$s on %2$s", 'string1', 'string2');
不起作用,而 printf('by %1$s on % 2$s', 'string1', 'string2');
确实如此。
我实际上正在设计一个 Wordpress 主题,并且非常紧密地遵循最初的二十个主题。奇怪的是,我在之前的所有 printf() 语句中都使用了双引号,没有任何问题。
printf("by %1$s on %2$s", 'string1', 'string2');
doesn't work, whereas printf('by %1$s on %2$s', 'string1', 'string2');
does.
I'm actually designing a Wordpress theme, and following the original twentyten theme very closely. The weird thing is, I've been using double quotation marks on all my previous printf() statements without any problems whatsoever.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为当您使用双引号时,
$s
被视为变量如:
where 使用时:
有关更详细的说明,您可以查看手册:
一般字符串
单引号 与 双引号
Because when you are using double quotes the
$s
is treated as a variableAs in:
where as when using:
For a more detailed explanation you can check the manual:
Strings in General
Single quoted vs Double quoted
认识到 php 对单引号和双引号字符串的处理方式是不同的,这一点非常重要。
您可以在官方 php 文档 中阅读更多内容,但让我给您一个突出显示:
将输出$t,其中
将输出bla
It is very important to realize php is treating single quoted and double quoted strings differently.
You can read more in official php docs, but let me give you a highlight:
will output $t, where
will output bla
那是因为字符串中有“$s”位。当使用双引号时,PHP 将其解释为变量并尝试解析它。您之前可能使用了不含
$
的双引号。That's because you have the '$s' bit in your string. When using double quotation marks PHP interprets it as a variable and tries to parse it. You probably used double quotations without the
$
in it earlier.正如其他答案所说,它将
$s
视为变量,您始终可以转义$
但我会使用单引号,因为 php 不需要解析字符串,因此速度更快。
As the other answers say, it treats
$s
as a variable, you could always escape the$
I would however use single quotation marks, as php doesn't need to parse the string and is therefore faster.