0

HTML 模板

<b><!--{NAME}--></b>
...
..
..
<b><!--{ADDRESS}--></b>

PHP 数组

array('name'=>'my full name', ..... , 'address'=>'some address ');

我有很多模板文件,必须解析它们中的每一个并将其替换为关联数组中的 str_replace 给定数据。

我需要你的建议来改进这个过程或任何其他可能有用的技术/工具

编辑:当前版本的代码

静态函数 ParseTemplate($data,$template){

    $html=$read==true ?  self::GetCached($template,true) : $template ;

    foreach($data as $key=>$value){
        if(is_array($value) ){
            foreach($data[$key] as $aval)
            $html = str_replace("<!--{".$key."}-->",$aval,$html);
        }
        else $html = str_replace("<!--{".$key."}-->",$value,$html);
    }

    return $html;

}

谢谢

4

3 回答 3

1

如果数组键始终与大括号内的模板单词相同,请执行以下操作:

foreach ($array as $key => $value) {
  $html = str_replace("<!--{$key}-->", $value, $html)
}

如果性能很重要,最好在 html 上使用 strpos,并逐个检查占位符。在大字符串上多次执行 str_replace 会更快。但如果性能不是问题,则没有必要。

编辑:

$index = strpos($html, "<!--");
while ( $index !== false ) {
  // get the position of the end of the placeholder
  $closing_index = strpos($html, "}-->", $index);

  // extract the placeholder, which is the key in the array
  $key = substr ($html, $index + 5, $closing_index);

  // slice the html. the substr up to the placeholder + the value in the array
  // + the substr after
  $html = substr ($html, 0, $index) . $array[$key] .
          substr ($html, $closing_index + 4);

  $index = strpos($html, "<!--", $index + 1);
}

注意:这未经测试,因此索引可能存在一些不准确之处......这只是为了给您一个大致的想法。

我认为这比 str_replace 更有效,但你知道吗?这可以使用一些基准测试...

于 2012-12-11T07:34:40.653 回答
1

为什么不使用Mustache之类的模板引擎,这里是PHP 版本

于 2012-12-12T01:42:25.857 回答
0

如果我正确理解了这个问题,我认为以下应该可以正常工作,除非我遗漏了什么。

$a = array('name'=>'my full name','address'=>'some address');
foreach($a as $k=>$v)
{
    $html = str_replace('<!--{'.strtoupper($k).'}-->',$v,$html);
}
于 2012-12-11T07:36:55.993 回答