簡體   English   中英

PHP 相當於 Python 的 `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'));
  1. 順序無所謂,
  2. 如果您希望它簡單地遞增(第一個匹配的{}將被轉換為{0}等),您可以省略名稱/號碼,
  3. 你可以命名你的參數,
  4. 您可以混合其他三個點。

我知道這是一個老問題,但我相信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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM