PHP equivalent of Python's `str.format` method?

后端 未结 3 2208
难免孤独
难免孤独 2021-02-19 21:06

Is there an equivalent of Python str.format in PHP?

In Python:

\"my {} {} cat\".format(\"red\", \"fat\")

All I see I can d

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-19 21:51

    I know it's an old question, but I believe strtr with replace pairs deserves to be mentioned:

    (PHP 4, PHP 5, PHP 7)

    strtr — Translate characters or replace substrings

    Description:

    strtr ( string $str , string $from , string $to ) : string
    strtr ( string $str , array $replace_pairs ) : string
    
     "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:

     "one",
            "test1" => "three",
            "{test1}" => "two",
            "{test2}" => "four"
        ]
    ));
    
    ?>
    
    string(22) "one two two three four"
    

提交回复
热议问题