PHP等价于python的's ' str.格式的方法


PHP equivalent of Python's `str.format` method?

在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的本地替代品?

sprintf是最接近的。这是老式的Python字符串格式:

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

由于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. 其他三个点可以混用

我知道这是一个老问题,但我相信strtr与替换对值得提及:

(php4, php5, php7)

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"
相关文章: