问题描述
我正在制作一个简单的PHP模板系统,但遇到一个我无法解决的错误,问题是布局加载效果很好,但是很多次,无法弄清楚如何解决,这里是我的代码
I'm making a simple PHP Template system but I'm getting an error I cannot solve, the thing is the layout loads excellent but many times, can't figure how to solve, here my code
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>');
}
}
}
输出为
标题为:欢迎使用我的模板系统
Title is : Welcome to my template system
贷方为[贷方]
标题为:[标题]
贷方对Alvaritos的贷方
Credits to Credits to Alvaritos
您可以看到这是错误的,但不知道如何解决。
As you can see this is wrong, but don't know how to solve it.
推荐答案
最好使用:
$content = file_get_contents($path);
$new = strtr($content, $this->vars);
print $new;
str_replace()
在定义键的顺序。如果您有像 array('a'=> 1,'aa'=> 2)
这样的变量和像 aa
,您将获得 11
而不是 2
。 strtr()
会在替换之前按长度对键进行排序(从高到低),这样就不会发生。
str_replace()
does the replaces in the order the keys are defined. If you have variables like array('a' => 1, 'aa' => 2)
and a string like aa
, you will get 11
instead of 2
. strtr()
will order the keys by length before replacing (highest first), so that won't happen.
这篇关于PHP foreach用数组覆盖值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!