发送到 str_replace PHP 时修改数组键
Modify array key when sent to str_replace PHP
我正在尝试在我的项目中使用 html 模板,到目前为止它正在运行,但为了使模板更易于使用,我想使用 {} 来表示字段区域。像这样:
//tplCall.html
<div id="{CustID}">
<div class="callname">{Name}</div>
<div class="calladdress">{Address}</div>
</div>
以下工作正常:
$tmpCall = file_get_contents("templates/tplCall.html");
$tmpdata = get_object_vars($thiscall);
$htmlout = str_replace(array_keys($tmpdata),array_values($tmpdata),$tmpCall);
echo $htmlout;
但显然保持 {} 完好无损。我想做类似下面的事情,但我得到一个数组到字符串的错误。如何在发送到 str_replace 之前将 {} 添加到密钥部分?
$tmpCall = file_get_contents("templates/tplCall.html");
$tmpdata = get_object_vars($thiscall);
$htmlout = str_replace("{" . array_keys($tmpdata) . "}",array_values($tmpdata),$tmpCall);
echo $htmlout;
显式修改array_keys($tmpdata)
的每个元素:
$keys = array_map(function($v) { return '{' . $v . '}'; }, array_keys($tmpdata));
// also there's no need to apply `array_values`
// as `str_replace` does not care about keys.
$htmlout = str_replace($keys, $tmpdata, $tmpCall);
我正在尝试在我的项目中使用 html 模板,到目前为止它正在运行,但为了使模板更易于使用,我想使用 {} 来表示字段区域。像这样:
//tplCall.html
<div id="{CustID}">
<div class="callname">{Name}</div>
<div class="calladdress">{Address}</div>
</div>
以下工作正常:
$tmpCall = file_get_contents("templates/tplCall.html");
$tmpdata = get_object_vars($thiscall);
$htmlout = str_replace(array_keys($tmpdata),array_values($tmpdata),$tmpCall);
echo $htmlout;
但显然保持 {} 完好无损。我想做类似下面的事情,但我得到一个数组到字符串的错误。如何在发送到 str_replace 之前将 {} 添加到密钥部分?
$tmpCall = file_get_contents("templates/tplCall.html");
$tmpdata = get_object_vars($thiscall);
$htmlout = str_replace("{" . array_keys($tmpdata) . "}",array_values($tmpdata),$tmpCall);
echo $htmlout;
显式修改array_keys($tmpdata)
的每个元素:
$keys = array_map(function($v) { return '{' . $v . '}'; }, array_keys($tmpdata));
// also there's no need to apply `array_values`
// as `str_replace` does not care about keys.
$htmlout = str_replace($keys, $tmpdata, $tmpCall);