Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to replace placeholders with variables [duplicate]

Tags:

php

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?

like image 915
OptimusCrime Avatar asked Nov 02 '11 13:11

OptimusCrime


2 Answers

What about strtr

$trans = array(
    '{{NAME}}' => $name, 
    "{{AGE}}"   => $age,
    ......
);
echo strtr($text, $trans);
like image 73
xdazz Avatar answered Nov 18 '22 06:11

xdazz


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];
}
like image 21
mario Avatar answered Nov 18 '22 06:11

mario