我正在编写一个简单的模板系统,用于在服务器上运行动态查询.
我最初在我的模板类中有以下代码:
$output = file_get_contents($this->file);
foreach ($this->values as $key => $value) {
$tagToReplace = "{$key}";
$output = str_replace($tagToReplace, $value, $output);
}
Run Code Online (Sandbox Code Playgroud)
我注意到字符串没有像我预期的那样被替换('{}'字符仍留在输出中).
然后我将"违规"行更改为:
$tagToReplace = '{'."$key".'}';
Run Code Online (Sandbox Code Playgroud)
然后按预期工作.为什么这种变化是必要的?解释字符串中的"{"在PHP中是否具有特殊意义?
是.当使用双引号,"{$key}"并且"$key"是相同的.通常这样做可以扩展更复杂的变量,例如"My name is: {$user['name']}".
你可以使用单引号(如你所知),转义大括号"\{$key\}"- 或者将变量包装两次:"{{$key}}".
在这里阅读更多:http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing