[英]How to use HTML as template in PHP?
我想使用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中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.