在printf()字符串中命名PHP说明符 [英] Name PHP specifiers in printf() strings
问题描述
PHP中是否可以像Python中那样命名说明符?
我想要在PHP中使用它:
$foo = array('name' => 24);
printf("%(name)d", $foo);
我在google或php手册中找不到任何相关内容.
很好的问题!
通过使用正则表达式,您可以自己滚动自己而没有太多麻烦.我基于调用 vsprintf
的想法来实现该实现内置printf
函数家族中最接近既定目标的
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);
}
要测试:
$foo = array('age' => 5, 'name' => 'john');
echo vsprintf_named("%(name)s is %(age)02d", $foo);
更新:我的最初实现非常满意.事实证明,一个超基本的foreach
就足够了,这也使该函数在PHP> = 4.1中可用(不是100%确定特定版本,但应该在那里).
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.
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).
这篇关于在printf()字符串中命名PHP说明符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!