php - 发送到 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);
推荐阅读
- phylogeny - 系统发育分析软件 (BAMM) 错误消息告诉我我的系统发育具有非正分支长度。我改变了这个,但错误仍然存在
- google-analytics - Google Analytics 目标未捕获所有事件
- image - 没有这样的图像:docker.io/openshift/origin-node-problem-detector:v3.11.0
- html - 自动填充(登录凭据)在 IE11 和 Edge 中不起作用
- coq - 自然数列表的拆分
- ios - iOS 中的 Firebase 身份验证以及 Swift 5 的最新更新
- python - 使用 pandas python 在 excel 文件中获取不相关的日期并创建标题并添加评论,例如“日期不相关”
- reactjs - 部署到 azure 应用服务时反应无效的主机头错误
- python - 在 Python 中将两个空列表之间的所有列表(字符串列表)合并为一个列表
- loopbackjs - 模型中的环回数据源特定配置