php - 如何在 PHP 中使用 HTML 作为模板?
问题描述
我想使用 html 作为模板并用 PHP 填充数据。如果我有一些 html 这种方式
<h1>${heading-1}</h1>
<p>${paragraph}</p>
我想用我的 PHP 数组中的匹配值替换模板标签。如果我有所有可能匹配的数组
$possible_matches = array(
'heading-1'=> 'You can\'t do anything',
'paragraph' => 'Unless you show your code which you don\'t have so be ready for down votes'
);
// what now?
它改变了像
<h1>You can't do anything</h1>
<p>Unless you show your code which you don't have so be ready for down votes</p>
我怎样才能做到这一点?我应该使用正则表达式吗?
解决方案
你可以像这样使用 foreach 循环和 str_replace
$html = '<h1>${heading-1}</h1>
<p>${paragraph}</p>';
$possible_matches = array(
'heading-1'=> 'You can\'t do anything',
'paragraph' => 'Unless you show your code which you don\'t have so be ready for down votes'
);
foreach($possible_matches as $key=> $value){
$html = str_replace('${'.$key.'}',$value,$html);
}
echo $html;
如果外部文件中包含 html 模板,您可以使用 file_get_contents 将 html 放入变量 $html
推荐阅读
- testing - NestJS - 测试 TCP 微服务
- r - R中的网络对象和邻接矩阵
- ios - Expo:上传到Apple App Store“跳过等待构建处理”
- perl - 宽字符和 Unicode 编码
- c++ - 覆盖 iostream << 导致错误 - C++ 11
- vuejs2 - 从 v-for 传递参数以动态更新 b-tab 标题
- powershell - 通过 PowerShell 从远程计算机上的服务器执行卸载设置
- python - python:如何首先根据值(可以为空/无/真/假)然后基于键对字典进行排序
- python - 使用 python3 在 pipenv 中设置 awscli
- java - 如何解决此“应用程序启动方法中的异常”