替换 .tpl 文件中的变量


Replace variables from .tpl file

此刻的情况

我正在使用这个函数:

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.');
    }        
}

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

问题

我想开始使用{$name}而不是在我的 TPL 文件中使用 <?php echo $name; ?>。谁能指出我用$tpl->name数据替换它的正确方向?

我尝试过什么

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

我可能会使用正则表达式,但这里有一个替代。 您也可以通过 $this->vars 键进行 foreach:

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

像这样的东西?

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

请注意,从 5.5 开始已弃用,如 PHP 手册中所述:http://php.net/manual/en/reference.pcre.pattern.modifiers.php