首页 > 解决方案 > 如何在 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>

我怎样才能做到这一点?我应该使用正则表达式吗?

标签: phphtmlparsingtemplates

解决方案


你可以像这样使用 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


推荐阅读