14

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
3
  • Some of the user-contributed notes and functions in PHP's documentation for sprintf come quite close. Note: search the page for "sprintf2". Commented 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. Commented Jun 22, 2017 at 19:32
  • @MarkBiek Do not include solution to question please (post a separate answer instead). Commented Jun 25 at 0:05

2 Answers 2

5
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
4

@Marius

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.