PHP 相当于 Python 的 `str.format` 方法吗? [英] PHP equivalent of Python's `str.format` method?
本文介绍了PHP 相当于 Python 的 `str.format` 方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
PHP 中是否有等效的 Python str.format
?
Is there an equivalent of Python str.format
in PHP?
在 Python 中:
In Python:
"my {} {} cat".format("red", "fat")
我在 PHP 中所能做的就是命名条目并使用 str_replace
:
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')
还有其他 PHP 的原生替代品吗?
Is there any other PHP's native alternatives?
推荐答案
由于 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'));
- 顺序无关紧要,
- 如果您想简单地增加名称/号码,您可以省略名称/号码(匹配的第一个
{}
将转换为{0}
等),立> - 您可以命名参数,
- 您可以混合其他三点.
这篇关于PHP 相当于 Python 的 `str.format` 方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文