在printf()字符串中命名PHP说明符 [英] Name PHP specifiers in printf() strings

查看:87
本文介绍了在printf()字符串中命名PHP说明符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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).

See it in action.

这篇关于在printf()字符串中命名PHP说明符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆