我试图了解更多关于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;
我是不是遗漏了什么?
我通常使用sprintf来确保来自用户输入的id是一个整数,例如:
// is better use prepared statements, but this is practical sometimes
$query = sprintf("SELECT * from articles where id = %d;",$_GET['article_id']);
Also是用来做基本的模板(html邮件或其他东西),所以你可以在很多地方重用模板:
$mail_body = "Hello %s, ...";
$oneMail = sprintf($mail_body, "Victor");
$anotherMail = sprintf($mail_body, "Juan");
用不同的表示形式(八进制、控制小数点等)格式化数字也非常有用。
Sprintf()非常类似于printf()。如果您了解printf()的详细信息,那么sprintf()甚至vsprintf()都不难理解。
sprintf()与printf()的一个不同之处在于,您需要声明一个变量来捕获函数的输出,因为它不直接打印/回显任何内容。让我们看看下面的代码片段:
printf("Hello %s", "world"); // "Hello world"
sprintf("Hello %s", "world"); // does not display anything
echo sprintf("Hello %s", "world"); // "Hello world"
$a = sprintf("Hello %s", "world"); // does not display anything
echo $a;// "Hello world"
希望这能有所帮助。
在循环中使用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秒