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

人盡茶涼 提交于 2020-01-13 07:58:07

问题


Is there an equivalent of Python str.format in PHP?

In Python:

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

All I see I can do in PHP natively is by naming the entries and using str_replace:

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

Is there any other PHP's native alternatives?


回答1:


sprintf is the closest thing. It's the old-style Python string formatting:

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



回答2:


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. The order doesn't matter,
  2. You can omit the name/number if you want it to simply increment (the first {} matched will be transformed into {0}, etc),
  3. You can name your parameters,
  4. You can mix the three other points.


来源:https://stackoverflow.com/questions/16632067/php-equivalent-of-pythons-str-format-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!