如何在PHP中使用HTML作为模板?

问题描述 投票:0回答:1

我想使用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?

它改变了html就好了

<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>

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

php html parsing templates
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.