![](/img/trans.png)
[英]Does PHP have a string function like Python's f-string function? (not str.format())
[英]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'));
{}
将被转换为{0}
等),您可以省略名称/号码,我知道这是一个老问题,但我相信strtr 与替换对值得一提:
(PHP 4、PHP 5、PHP 7)
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.