我试图了解更多关于PHP函数sprintf(),但php.net没有帮助我,因为我仍然困惑,为什么要使用它?

看看下面的例子。

为什么用这个:

$output = sprintf("Here is the result: %s for this date %s", $result, $date);

当这样做是一样的,更容易写IMO:

$output = 'Here is the result: ' .$result. ' for this date ' .$date;

我是不是遗漏了什么?


当前回答

我发现的最好的理由是,它允许你把所有的语言字符串放在你的语言文件中,人们可以根据需要翻译和排序它们-但你仍然知道,无论字符串的格式是什么-你希望显示用户的名字。

例如,您的网站会在页面顶部显示“欢迎返回[[User]]”。作为程序员,你不知道或不关心UI人员将如何编写它——你只知道用户名将显示在消息中的某个地方。

因此,您可以将消息嵌入到代码中,而不必担心该消息实际上是什么。

只需文件 (EN_US):

...
$lang['welcome_message'] = 'Welcome back %s';
...

然后,通过在实际的php代码中使用它,就可以支持任何语言的任何类型的消息。

sprintf($lang['welcome_message'], $user->name())

其他回答

参数与使用模板的参数相同。您需要将Textsleev与实际的变量值分开。除了我们提到的sprintf的额外功能之外,它只是一个样式问题。

sprintf的另一个用途是在本地化的应用程序中,因为sprintf的参数不必按照它们在格式字符串中出现的顺序排列。

例子:

$color = 'blue';
$item = 'pen';

sprintf('I have a %s %s', $color, $item);

但是像法语这样的语言对单词的顺序是不同的:

$color = 'bleu';
$item = 'stylo';

sprintf('J\'ai un %2$s %1$s', $color, $item);

(是的,我的法语很烂:我在学校学过德语!)

实际上,您可以使用gettext来存储本地化的字符串,但您可以理解。


在循环中使用sprintf时必须小心:

$a = 'Anton';
$b = 'Bert';
$c = 'Corni';
$d = 'Dora';
$e = 'Emiel';
$f = 'Falk';
$loops = 10000000;

$time = microtime(true);

for ($i = 0; $i < $loops; $i++)
{
    $test = $a . $b . $c . $d . $e . $f;
}

$concatTime = microtime(true) - $time;

$time = microtime(true);

for ($i = 0; $i < $loops; $i++)
{
    $test = "$a $b $c $d $e $f";
}

$concat2Time = microtime(true) - $time;

$time = microtime(true);

for ($i = 0; $i < $loops; $i++)
{
    $test = sprintf('%s %s %s %s %s %s', $a, $b, $c, $d, $e, $f);
}

$sprintfTime = microtime(true) - $time;

echo 'Loops: ' . $loops . '<br>';
echo '\'$a . $b . $c . $d . $e . $f\'' . ' needs ' . $concatTime  . 's<br>';
echo '"$a $b $c $d $e $f"' . ' needs ' . $concat2Time  . 's<br>';
echo 'sprintf(\'%s %s %s %s %s %s\', $a, $b, $c, $d, $e, $f)' . ' needs ' . $sprintfTime  . 's<br>';

这会导致以下时间(在我的本地机器上使用PHP 7.2):

循环:10000000

“一美元。b美元。$ c。美元d。$ e。$f'需要1.4507689476013s

“$a $b $c $d $e $f”需要1.9958319664001s

sprintf (' % s % s % s % s % s % s’,一个美元,美元b, c,美元美元d, e,美元$ f)需要9.1771278381348秒

众所周知,sprintf有很多功能 一个例子如下:

几个月前,我需要将秒转换为小时:分钟:秒的格式 像$t = 494050 //秒,我想打印像137 h 14 m 10 s,所以我提出了php函数springf(),我只是保持秒在$t和回声sprintf(“%02d h %s%02d m %s%02d s”,地板($t/3600), $f, ($t/60)%60, $f, $t%60);得到137小时14米10秒

Sprintf()函数是一个非常有用的函数,如果我们知道如何使用它。

在一些典型的情况下,您需要更精确地控制输出格式。例如,根据特定值的长度,确保特定值前面填充了特定数量的空格,或者以特定的精确格式输出数字,这可能很棘手。

在PHP手册中有很多例子

还有你的“更容易写”的例子。虽然echo可能更容易编写,但sprintf更容易读取,特别是在有很多变量的情况下。

使用sprintf或printf的另一个原因可能是您希望让用户定义某些值的输出格式—您可以安全地允许他们定义与sprintf兼容的输出格式。

哦,你的例子有一部分是错的。Sprintf返回字符串,但echo不返回——echo立即输出它并且不返回任何东西,而Sprintf只是返回它。