为什么双引号字符串内的变量周围的大括号不按字面意思处理?

发布于 2024-12-28 14:59:37 字数 452 浏览 2 评论 0原文

我正在编写一个简单的模板系统,用于在服务器上运行动态查询。

我最初在模板类中有以下代码:

$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

暖阳 2025-01-04 14:59:37

是的。使用双引号时,"{$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

失与倦" 2025-01-04 14:59:37

是的。它确实有助于解析变量名称。看看这个问题

{} 可以按如下方式使用:

$test = "something {$foo->awesome} value.";

顺便说一下,您可以使用以下内容进一步改进您的代码(从而避免您现在遇到的情况):

$output = file_get_contents($this->file);
$output = str_replace(array_keys($this->values), $this->values, $output);

Yes. It does help to resolve variable names. Take a look at this question.

{ and } can used as follow:

$test = "something {$foo->awesome} value.";

By the way, you can further improve your code by using the following (and thus avoiding the situation you're having right now):

$output = file_get_contents($this->file);
$output = str_replace(array_keys($this->values), $this->values, $output);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文