Possible Duplicate:
replace multiple placeholders with php?
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.
Is there no better way than str_replace?
What about strtr
$trans = array(
'{{NAME}}' => $name,
"{{AGE}}" => $age,
......
);
echo strtr($text, $trans);
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).
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With