Return to Snippet

Revision: 64657
at September 4, 2013 01:56 by ourlaputa

Initial Code
function vsprintf_named($format, $args) {
    $names = preg_match_all('/%\((.*?)\)/', $format, $matches, PREG_SET_ORDER);

    $values = array();
    foreach($matches as $match) {
        $values[] = $args[$match[1]];

    $format = preg_replace('/%\((.*?)\)/', '%', $format);
    return vsprintf($format, $values);

Initial URL

Initial Description
Taken from stackoverflow answer by user Jon

To test
    $foo = array('age' => 5, 'name' => 'john');
    echo vsprintf_named("%(name)s is %(age)02d", $foo);

Initial Title
Named specifier in php formatted strings, similar to Python\'s formatted strings using dictionaries

Initial Tags

Initial Language