[英]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.