简体   繁体   English

什么是在PHP中解析这样的模板的有效方法?

[英]what is the efficient way to parse a template like this in php?

HTML template HTML模板

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

PHP Array PHP数组

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

I have lots of template files and have to parse each of them and replace it the str_replace given data in associative arrays. 我有很多模板文件,必须解析每个模板文件并将其替换为关联数组中的str_replace给定数据。

I need your suggestions to improve this process or any other technique/tool that might be helpful 我需要您的建议来改进此过程或任何其他可能有用的技术/工具

Edit: Current version of code 编辑:当前版本的代码

static function ParseTemplate($data,$template){ 静态函数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;

} }

thanks 谢谢

if the array keys are always the same as the template word inside the braces, do something like this: 如果数组键总是与大括号内的模板字相同,请执行以下操作:

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

if performance is important, it may be better to use strpos on the html, and go over the placeholders one by one. 如果性能很重要,最好在html上使用strpos,然后逐个遍历占位符。 it will be quicker that doing str_replace many times on a large string. 在一个大字符串上多次执行str_replace会更快。 but if performance is not an issue, it's not necessary. 但如果表现不是问题,则没有必要。

EDIT: 编辑:

$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);
}

NOTE: this wasn't tested, so there may be some inaccuracies with the indexes... it's just to give you a general idea. 注意:这没有经过测试,因此索引可能存在一些不准确之处......这只是为了给您一个大致的想法。

I think this is more efficient then str_replace, but you know what? 我认为这比str_replace更有效,但你知道吗? this can use some benchmarking... 这可以使用一些基准测试......

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

If I understand the question correctly, I think the following should work fine unless I'm missing something. 如果我正确地理解了这个问题,我认为以下情况应该可以正常工作,除非我遗漏了一些东西。

$a = array('name'=>'my full name','address'=>'some address');
foreach($a as $k=>$v)
{
    $html = str_replace('<!--{'.strtoupper($k).'}-->',$v,$html);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM