PHP foreach用数组覆盖值


PHP foreach overwrite value with array

我正在制作一个简单的PHP模板系统,但我遇到了一个无法解决的错误,问题是布局加载很好,但很多次都不知道如何解决,这里是我的代码

Class Template {
private $var = array();
public function assign($key, $value) {
    $this->vars[$key] = $value;
}
public function render($template_name) {
    $path = $template_name.'.tpl';
    if (file_exists($path)) {
        $content = file_get_contents($path);
        foreach($this->vars as $display) {

            $newcontent = str_replace(array_keys($this->vars, $display), $display, $content);
            echo $newcontent;
        }
    } else {
        exit('<h1>Load error</h1>');
    }
}

}

输出为

标题是:欢迎使用我的模板系统

【信用】的信用

标题为:[标题]

信用证至信用证至Alvaritos

正如你所看到的,这是错误的,但不知道如何解决它。

您最好使用strtr:

$content = file_get_contents($path);
$new = strtr($content, $this->vars);
print $new;

str_replace()按照键的定义顺序进行替换。如果您有像array('a' => 1, 'aa' => 2)这样的变量和像aa这样的字符串,您将得到11而不是2strtr()将在替换之前按长度对密钥进行排序(最高优先),这样就不会发生这种情况。

使用此:

foreach($this->vars as $key => $value)
    $content = str_replace($key,$value,$content);
echo $content;