preg_replace for template calling function,提供替换匹配表达式的数据

时间:2014-08-15 09:46:18

标签: php templates

我有一个模板,其中包含以下要替换的标记:

%www_authorList

%www_titleHome

我有一个同名的函数

public function authorList
{

}
public function titleHome
{

}  

我想用函数返回的文本搜索和替换标记。在PHP中有可能吗?因为它可能在perl ...

我的代码尝试替换

     $this->file = file_get_contents($template);
     $this->file = preg_replace("/%www_(\w+)/", "$this->$1()", $this->file);

在perl中,以下行也是如此:

    my $libObj =  new libs;  
    $data =~ s/%www_(\w+)/$libObj->$1()/ge;

1 个答案:

答案 0 :(得分:0)

看起来你需要"双重间接"在这里,例如:

class Template
{
    public function authorList()
    {
        return 'auth';
    }
    public function titleHome()
    {
        return 'title';
    }
    public function run($text) {
        return preg_replace_callback("/%www_(\w+)/", array($this, 'replace'), $text);
    }
    protected function replace($matches) {
        return $this->{$matches[1]}();
    }
}

$t = new Template();
echo $t->run("%www_authorList and %www_titleHome"); // auth and title

php确实有e标记,但它discouraged and deprecated as of php 5.5不会使用它。