PHP相当于Python的`str.format`方法?

Jer*_*meJ 11 php python replace language-comparisons

str.format在PHP中是否有相当于Python 的东西?

在Python中:

"my {} {} cat".format("red", "fat")
Run Code Online (Sandbox Code Playgroud)

所有我认为我可以用PHP本身做的就是命名条目并使用str_replace:

str_replace(array('{attr1}', '{attr2}'), array('red', 'fat'), 'my {attr1} {attr2} cat')
Run Code Online (Sandbox Code Playgroud)

还有其他PHP的原生替代品吗?

Ble*_*der 8

sprintf是最接近的事情.这是旧式的Python字符串格式:

sprintf("my %s %s cat", "red", "fat")
Run Code Online (Sandbox Code Playgroud)


Jer*_*meJ 7

由于PHP str.format在Python 中没有真正的替代品,所以我决定实现我非常简单的自己,这是Python的大多数基本功能.

function format($msg, $vars)
{
    $vars = (array)$vars;

    $msg = preg_replace_callback('#\{\}#', function($r){
        static $i = 0;
        return '{'.($i++).'}';
    }, $msg);

    return str_replace(
        array_map(function($k) {
            return '{'.$k.'}';
        }, array_keys($vars)),

        array_values($vars),

        $msg
    );
}

# Samples:

# Hello foo and bar
echo format('Hello {} and {}.', array('foo', 'bar'));

# Hello Mom
echo format('Hello {}', 'Mom');

# Hello foo, bar and foo
echo format('Hello {}, {1} and {0}', array('foo', 'bar'));

# I'm not a fool nor a bar
echo format('I\'m not a {foo} nor a {}', array('foo' => 'fool', 'bar'));
Run Code Online (Sandbox Code Playgroud)
  1. 订单无关紧要,
  2. 您可以省略名称/号码,如果您希望它只是递增(第一个{}匹配将被转换为{0}等),
  3. 你可以命名你的参数,
  4. 你可以混合其他三个点.