<p>Python has this wonderful way of handling string substitutions using dictionaries:</p>

<pre><code>&gt;&gt;&gt; 'The %(site)s site %(adj)s because it %(adj)s' % {'site':'Stackoverflow', 'adj':'rocks'}
'The Stackoverflow site rocks because it rocks'
</code></pre>

<p>I love this because you can specify a value once in the dictionary and then replace it all over the place in the string.</p>

<p>I've tried to achieve something similar in PHP using various string replace functions but everything I've come up with feels awkward.</p>

<p>Does anybody have a nice clean way to do this kind of string substitution in PHP?</p>

<p><strong><em>Edit</em></strong><br>
Here's the code from the sprintf page that I liked best.  </p>

<pre><code>&lt;?php

function sprintf3($str, $vars, $char = '%')
{
    $tmp = array();
    foreach($vars as $k =&gt; $v)
    {
        $tmp[$char . $k . $char] = $v;
    }
    return str_replace(array_keys($tmp), array_values($tmp), $str);
}

echo sprintf3( 'The %site% site %adj% because it %adj%', array('site'=&gt;'Stackoverflow', 'adj'=&gt;'rocks'));
?&gt;
</code></pre>

[{'answer_id': 28199, 'author': 'Tom Mayfield', 'author_id': 2314, 'author_profile': 'https://Stackoverflow.com/users/2314', 'pm_score': 1, 'selected': False, 'text': '<p>Some of the user-contributed notes and functions in <a href="http://us3.php.net/sprintf" rel="nofollow noreferrer">PHP\'s documentation for sprintf</a> come quite close.</p>\n\n<p>Note: search the page for "sprintf2".</p>\n'}, {'answer_id': 28247, 'author': 'Marius', 'author_id': 1585, 'author_profile': 'https://Stackoverflow.com/users/1585', 'pm_score': 4, 'selected': True, 'text': '<pre><code>function subst($str, $dict){\n    return preg_replace(array_map(create_function(\'$a\', \'return "/%\\\\($a\\\\)s/";\'), array_keys($dict)), array_values($dict), $str);\n }\n</code></pre>\n\n<p>You call it like so:</p>\n\n<pre><code>echo subst(\'The %(site)s site %(adj)s because it %(adj)s\', array(\'site\'=&gt;\'Stackoverflow\', \'adj\'=&gt;\'rocks\'));\n</code></pre>\n'}, {'answer_id': 28349, 'author': 'Gary Richardson', 'author_id': 2506, 'author_profile': 'https://Stackoverflow.com/users/2506', 'pm_score': 2, 'selected': False, 'text': '<p>@<a href="https://stackoverflow.com/questions/28165/does-php-have-an-equivalent-to-this-type-of-python-string-substitution#28199">Marius</a></p>\n\n<p>I don\'t know if it\'s faster, but you can do it without regexes:</p>\n\n<pre><code>function subst($str, $dict)\n{\n  foreach ($dict AS $key, $value)\n  {\n    $str = str_replace($key, $value, $str);\n  }\n\n  return $str;\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/28165', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/305/']