Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Name PHP specifiers in printf() strings

Is there a way in PHP to name my specifiers like in Python?

I want this in PHP:

$foo = array('name' => 24);
printf("%(name)d", $foo);

I couldn't find nothing related on google or in the php manual.

like image 211
Paul Avatar asked Sep 15 '11 17:09

Paul


People also ask

What is the format specifier to print a string?

We can print the string using %s format specifier in printf function.


2 Answers

Nice question!

You can roll your own without too much trouble by working with regexes. I based the implementation on the idea of calling vsprintf, which is closest to the stated goal among the built-in printf family of functions:

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);
}

To test:

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

Update: My initial implementation was very lambda-happy. Turns out a super basic foreach will suffice, which also makes the function usable in PHP >= 4.1 (not 100% sure about the specific version, but should be around there).

See it in action.

like image 105
Jon Avatar answered Sep 29 '22 00:09

Jon


Use strtr:

$foo = array('%name%' => 24);
strtr("%name%", $foo); // 24

You could also do this:

"${foo['name']}"

Or this:

$name = 24;
"$name"
like image 35
Arnaud Le Blanc Avatar answered Sep 29 '22 01:09

Arnaud Le Blanc