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?
user4157124
2,99919 gold badges31 silver badges48 bronze badges
asked Aug 26, 2008 at 14:20
-
Some of the user-contributed notes and functions in PHP's documentation for sprintf come quite close. Note: search the page for "sprintf2".Tom Mayfield– Tom Mayfield2008年08月26日 14:30:17 +00:00Commented Aug 26, 2008 at 14:30
-
The workarounds suggested here so far should be taken as a "No" answer to the question in the OP. So far none of them appear to replicate the functionality of Python, and there are expressly identified bugs strewn throughout.dreftymac– dreftymac2017年06月22日 19:32:48 +00:00Commented Jun 22, 2017 at 19:32
-
@MarkBiek Do not include solution to question please (post a separate answer instead).user4157124– user41571242025年06月25日 00:05:17 +00:00Commented Jun 25 at 0:05
2 Answers 2
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'));
answered Aug 26, 2008 at 14:49
I don't know if it's faster, but you can do it without regexes:
function subst($str, $dict)
{
foreach ($dict AS $key, $value)
{
$str = str_replace($key, $value, $str);
}
return $str;
}
answered Aug 26, 2008 at 15:21
default