Name PHP specifiers in printf() strings

别来无恙 提交于 2019-12-12 08:25:09

问题


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.


回答1:


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.




回答2:


Use strtr:

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

You could also do this:

"${foo['name']}"

Or this:

$name = 24;
"$name"



回答3:


You can do it with sprintf by numbering the parameters, like so:

echo sprintf('hello, %2$s. What is your %1$s', 'age', 'Jesse');


Outputs the following string:

hello, Jesse. What is your age




回答4:


the closer core function is vsprintf() to use an array instead of multiple parameter, but you still have to use numbered parameters.

in the comments of this function docs there is someone who created a function to do what you want vnsprintf() printf+array+named parameters



来源:https://stackoverflow.com/questions/7435233/name-php-specifiers-in-printf-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!