Python has this wonderful way of handling string substitutions using dictionaries:
>>> 'The %(site)s site %(adj)s because it %(adj)s' % {'site':'Stackoverflow', 'adj':'rocks'}
'The Stackoverflow site rocks because it rocks'
I love this because you can specify a value once in the dictionary and then replace it all over the place in the string.
I've tried to achieve something similar in PHP using various string replace functions but everything I've come up with feels awkward.
Does anybody have a nice clean way to do this kind of string substitution in PHP?
function subst($str, $dict){
return preg_replace(array_map(create_function('$a', 'return "/%\\($a\\)s/";'), array_keys($dict)), array_values($dict), $str);
}
You call it like so:
echo subst('The %(site)s site %(adj)s because it %(adj)s', array('site'=>'Stackoverflow', 'adj'=>'rocks'));