tags:

views:

774

answers:

4

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 to similar to this 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?

Edit
Here's the code from the sprintf page that I liked best.

<?php

function sprintf3($str, $vars, $char = '%')
{
    $tmp = array();
    foreach($vars as $k => $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'=>'Stackoverflow', 'adj'=>'rocks'));
?>

Thanks Thomas!

Extra thanks to Marius. That solution is exactly what I was looking for.

+1  A: 

Some of the user-contributed notes and functions in PHP's documentation for sprintf come quite close.

Note: search the page for "sprintf2".

Thomas G. Mayfield
+4  A: 
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'));
Marius
+3  A: 

@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;
}
Gary Richardson
A: 

I didn't know you could do that in Python; I thought that was one thing Ruby had over both Python's and C#'s string formatting techniques. Thanks for showing me this!

pbh101