【问题标题】:PHP equivalent of Python's `str.format` method?PHP 相当于 Python 的`str.format` 方法?
【发布时间】:2013-05-13 23:32:30
【问题描述】:

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 的原生替代品吗?

【问题讨论】:

标签: php python replace language-comparisons


【解决方案1】:

sprintf 是最接近的东西。这是老式的 Python 字符串格式:

sprintf("my %s %s cat", "red", "fat")

【讨论】:

  • 我从不喜欢旧的 % 风格的格式,但我想如果没有更好的办法的话。
【解决方案2】:

由于 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. 您可以混合使用其他三个点。

【讨论】:

  • 当您想要输出一对花括号而不将其解释为变量的占位符时会发生什么?
  • @dreftymac 一个简单的解决方法是匹配(?<!\{)\{\}(?!\}) 而不仅仅是\{\} (负面看后面/前面)所以{{}} 没有被匹配然后将所有{{}} 替换为{}。 (遗憾的是,它也会留下{{}{}},但这没关系,对吧?)。告诉我是否应该编辑我的代码以反映这一点。
  • 没问题,我想我想说的基本观点是,在 PHP 中复制 str.format() 并不是一件容易的事。
  • 我主要需要它的基本用法,我很满意它的简洁性,但它肯定不是详尽无遗的。 :) 没有声称它是。感谢您的意见。
【解决方案3】:

我知道这是一个老问题,但我相信 strtr with replace pairs 值得一提:

(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"

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-10-10
  • 2010-10-28
  • 1970-01-01
  • 2012-12-03
  • 1970-01-01
  • 2014-06-17
  • 1970-01-01
  • 2011-09-18
相关资源
最近更新 更多