More elegant way to parse inline variables in strings
Posted
by
Tom
on Stack Overflow
See other posts from Stack Overflow
or by Tom
Published on 2011-12-10T23:12:09Z
Indexed on
2012/11/09
23:00 UTC
Read the original article
Hit count: 220
Currently I have this:
function parse_string($string, $variables){
extract($variables);
return eval('return "'. addcslashes($string, '"') .'";');
}
So I can input this string:
'Hi {$name}, my name is {$own_name}'
Together with this array:
array('name' => 'John', 'own_name' => 'Tom')
And get this back:
'Hi John, my name is Tom'
I've never liked this eval()
approach but it works and it's fast (faster than regex at least).
Question: Is there a more elegant way to do this (faster than using regex) in PHP5?
© Stack Overflow or respective owner