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

时间:2013-05-19 06:35:20

标签: php python replace language-comparisons

PHP中是否有等效的Python str.format

在Python中:

"my {} {} cat".format("red", "fat")

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

str_replace(array('{attr1}', '{attr2}'), array('red', 'fat'), 'my {attr1} {attr2} cat')

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

3 个答案:

答案 0 :(得分:8)

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

sprintf("my %s %s cat", "red", "fat")

答案 1 :(得分:5)

由于PHP在Python中没有真正替代str.format,我决定实现我非常简单的自己,这是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'));
  1. 订单无关紧要,
  2. 您可以省略名称/号码,如果您希望它只是递增(匹配的第一个{}将转换为{0}等),
  3. 您可以为参数命名,
  4. 你可以混合其他三个点。

答案 2 :(得分:0)

我知道这是一个古老的问题,但是我认为值得一提的是strtr with replace pairs

(PHP 4,PHP 5,PHP 7)

strtr —翻译字符或替换子字符串

说明:

strtr ( string $str , string $from , string $to ) : string
strtr ( string $str , array $replace_pairs ) : string
<?php
var_dump(
strtr(
    "test {test1} {test1} test1 {test2}",
    [
        "{test1}" => "two",
        "{test2}" => "four",
        "test1" => "three",
        "test" => "one"
    ]
));

?>

此代码将输出:

string(22) "one two two three four" 

即使更改数组项的顺序也会生成相同的输出:

<?php
var_dump(
strtr(
    "test {test1} {test1} test1 {test2}",
    [
        "test" => "one",
        "test1" => "three",
        "{test1}" => "two",
        "{test2}" => "four"
    ]
));

?>

string(22) "one two two three four"