OptimusCrime OptimusCrime - 11 months ago 68
PHP Question

Efficient way to replace placeholders with variables

Possible Duplicate:

replace multiple placeholders with php?

I've got a .txt-file working as a template. I've made several placeholders like
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?

Answer Source

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];