且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-06-23 05:31:50

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

As PHP doesn't really have a proper alternative to str.format in Python, I decided to implement my very simple own which as most of the basic functionnalitites of the Python's one.

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. 您可以混合其他三点.