[英]PHP equivalent of Python's `str.format` method?
Is there an equivalent of Python str.format
in PHP? PHP 中是否有等效的 Python
str.format
?
In Python:在 Python 中:
"my {} {} cat".format("red", "fat")
All I see I can do in PHP natively is by naming the entries and using str_replace
:我在 PHP 中所能做的就是命名条目并使用
str_replace
:
str_replace(array('{attr1}', '{attr2}'), array('red', 'fat'), 'my {attr1} {attr2} cat')
Is there any other PHP's native alternatives?有没有其他 PHP 的本机替代品?
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.由于 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'));
{}
matched will be transformed into {0}
, etc),{}
将被转换为{0}
等),您可以省略名称/号码,I know it's an old question, but I believe strtr with replace pairs deserves to be mentioned:我知道这是一个老问题,但我相信strtr 与替换对值得一提:
(PHP 4, PHP 5, PHP 7)
(PHP 4、PHP 5、PHP 7)
strtr — Translate characters or replace substrings
strtr — 翻译字符或替换子字符串
Description:
描述:
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"
]
));
?>
this code would output:此代码将输出:
string(22) "one two two three four"
Same output is generated even if you change the array items order:即使更改数组项顺序,也会生成相同的输出:
<?php
var_dump(
strtr(
"test {test1} {test1} test1 {test2}",
[
"test" => "one",
"test1" => "three",
"{test1}" => "two",
"{test2}" => "four"
]
));
?>
string(22) "one two two three four"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.