替换.tpl文件中的变量

时间:2013-11-04 15:44:24

标签: php templates

此时的情况

我正在使用此功能:

public function fetch($file){        
    $file = $this->options['template_dir'].(string)$file;

    if(file_exists($file)){
        ob_start();
        if($this->options['extract']){
            extract($this->vars);
        }
        include $file;
        return ob_get_clean();
    }else{
        throw new Exception('De ('.$file.') template bestaat niet.');
    }        
}

基本上它只是用<?php echo $name; ?>的数据替换tpl中的$tpl->name

问题

我想开始使用{$name}而不是在我的TPL文件中使用<?php echo $name; ?>。任何人都可以指出我正确的方向用$tpl->name

的数据替换它

我尝试了什么

我尝试使用正则表达式,尝试找到{和}然后替换它,但它只会输出$name作为文本。

2 个答案:

答案 0 :(得分:0)

这样的东西?

preg_replace("/\{(.+)\}/e", "$1", $template);

请注意,不推荐使用5.5,如php手册中所述:http://php.net/manual/en/reference.pcre.pattern.modifiers.php

答案 1 :(得分:0)

我可能会使用正则表达式,但这里是替代品。你也可以通过$ this-&gt; vars键来预告:

$template = file_get_contents($file);
$vars     = explode(',', '{$'.implode('},{$', array_keys($this->vars)).'}');
$output   = str_replace($vars, $this->vars, $template);
相关问题