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?
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