为什么双引号字符串内的变量周围的大括号不按字面意思处理?
我正在编写一个简单的模板系统,用于在服务器上运行动态查询。
我最初在模板类中有以下代码:
$output = file_get_contents($this->file);
foreach ($this->values as $key => $value) {
$tagToReplace = "{$key}";
$output = str_replace($tagToReplace, $value, $output);
}
我注意到字符串没有按照我的预期被替换(“{}”字符仍然保留在输出中)。
然后我将“有问题的”行更改为:
$tagToReplace = '{'."$key".'}';
然后它按预期工作。为什么需要进行此更改?解释字符串中的“{”在 PHP 中是否有特殊意义?
I am writing a trivial templating system for running dynamic queries on a server.
I originally had the following code in my templating class:
$output = file_get_contents($this->file);
foreach ($this->values as $key => $value) {
$tagToReplace = "{$key}";
$output = str_replace($tagToReplace, $value, $output);
}
I notice that the strings were not being replaced as I expected (the '{}' characters were still left in the output) .
I then changed the 'offending' line to:
$tagToReplace = '{'."$key".'}';
It then worked as expected. Why was this change necessary?. Does "{" in an interpreted string have special significance in PHP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的。使用双引号时,
"{$key}"
和"$key"
相同。通常这样做是为了可以扩展更复杂的变量,例如“我的名字是:{$user['name']}”
。您可以使用单引号(如您所用),转义大括号 -
"\{$key\}"
- 或将变量包装两次:"{{$key}}"< /代码>。
在这里阅读更多内容: http://www .php.net/manual/en/language.types.string.php#language.types.string.parsing
Yes. When using double quotes,
"{$key}"
and"$key"
are the same. It's usually done so you can expand more complex variables, such as"My name is: {$user['name']}"
.You can use single quotes (as you have), escape the curly brackets -
"\{$key\}"
- or wrap the variable twice:"{{$key}}"
.Read more here: http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing
是的。它确实有助于解析变量名称。看看这个问题。
{
和}
可以按如下方式使用:顺便说一下,您可以使用以下内容进一步改进您的代码(从而避免您现在遇到的情况):
Yes. It does help to resolve variable names. Take a look at this question.
{
and}
can used as follow:By the way, you can further improve your code by using the following (and thus avoiding the situation you're having right now):