PHP 中有没有一种方法可以像 Python 一样命名我的说明符?
我想要这个 PHP 版本:
$foo = array('name' => 24);
printf("%(name)d", $foo);
我在 google 或 php 手册中找不到任何相关内容。
好问题!
通过使用正则表达式,您可以轻松地推出自己的产品。我的实现基于调用的想法vsprintf http://www.php.net/manual/en/function.vsprintf.php,这是内置目标中最接近既定目标的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);
}
To test:
$foo = array('age' => 5, 'name' => 'john');
echo vsprintf_named("%(name)s is %(age)02d", $foo);
Update:我最初的实现对 lambda 非常满意。原来是一个超级基本的foreach
就足够了,这也使得该函数可以在 PHP >= 4.1 中使用(不能 100% 确定特定版本,但应该在那里)。
查看实际效果 http://ideone.com/z1KF4.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)