Efficient way to replace placeholders with variables

Possible duplicate:
replace multiple placeholders with php?

I have a .txt file working as a template. I made some placeholders, for example {{NAME}} , and I would like to replace them with variables. What is the most efficient way to do this? Keep in mind that I have about 10 such placeholders in my template.

Is there a better way than str_replace?

+4
source share
3 answers

str_replace not only ugly, but also sluggish if you need to replace ten variables (performs a binary search and starts from the beginning for each alternative).

Rather, use preg_replace_callback , either by listing all 10 variables at once, or using a late search:

 $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]; } 
+7
source

How about strtr

 $trans = array( '{{NAME}}' => $name, "{{AGE}}" => $age, ...... ); echo strtr($text, $trans); 
+14
source

What is so ugly about str_replace() ?

 function replace_vars($string) { $vars = array('NAME'=>'Name', 'VAR2'=>'Value 2', 'VAR3'=>'Value 3'); $names = array(); foreach($vars as $name=>$var) { $names[] = '{{'.$name.'}'; } return str_replace($names, $vars, $string); } 

or

 function replace_vars($string) { $vars = array('{{NAME}}'=>'Name', '{{VAR2}}'=>'Value 2', '{{VAR3}}'=>'Value 3'); return str_replace(array_keys($vars), $vars, $string); } 
0
source

Source: https://habr.com/ru/post/1379307/


All Articles