首页 > 解决方案 > 发送到 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;

标签: phparraysstr-replace

解决方案


显式修改每个元素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);

推荐阅读