用变量替换占位符的有效方法
可能重复:
用php替换多个占位符?
Possible Duplicate:
replace multiple placeholders with php?
我有一个.txt文件作为模板.我做了几个占位符,如{{NAME}}
,我想用变量替换它们.最有效的方法是什么?请记住,我的模板中大约有10个这些占位符.
I've got a .txt-file working as a template. I've made several placeholders like {{NAME}}
and I'd like to replace these with variables. What is the most efficient way to do this? Keep in mind that I have around 10 of these placeholders in my template.
没有比str_replace更好的方法了吗?
Is there no better way than str_replace?
str_replace
不仅丑陋,而且如果您需要替换十个变量,也会很迟钝(进行二进制搜索并从每个替代方法的开头开始).
str_replace
is not only ugly, but also sluggish if you need to replace ten variables (does a binary search and starts from the beginning for each alternative).
宁可使用 preg_replace_callback
,一次列出所有10个变量,也可以使用后向查找:
Rather use a preg_replace_callback
, either listing all 10 variables at once, or using a late-lookup:
$src = preg_replace_callback('/\{\{(\w+)}}/', 'replace_vars', $src);
# or (NAME|THING|FOO|BAR|FIVE|SIX|SVN|EGT|NNE|TEN)
function replace_vars($match) {
list ($_, $name) = $match;
if (isset($this->vars[$name])) return $this->vars[$name];
}