我试图了解更多关于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()格式化字符串更干净、更安全。

例如,在处理输入变量时,可以通过提前指定预期格式(例如,您期望字符串[%s]或数字[%d])来防止意外的意外。这可能有助于潜在的SQL注入风险,但它不会阻止如果字符串包含引号。

它还有助于处理浮点数,你可以显式地指定数字精度(例如%.2f),这可以节省你使用转换函数。

另一个优点是,大多数主流编程语言都有自己的sprintf()实现,因此一旦熟悉了它,它就更容易使用,而不是学习一门新的语言(比如如何连接字符串或转换浮点数)。

总之,这是一种很好的实践,可以让代码更清晰、更易读。

例如,请看下面的真实例子:

$insert .= "('".$tr[0]."','".$tr[0]."','".$tr[0]."','".$tr[0]."'),";

或者一些简单的例子,打印。' 1 ', ' 2 ', ' 3 ', ' 4 ':

print "foo: '" . $a . "','" . $b . "'; bar: '" . $c . "','" . $d . "'" . "\n";

和打印格式化字符串:

printf("foo: '%d','%d'; bar: '%d','%d'\n", $a, $b, $c, $d);

其中printf()相当于sprintf(),但它输出一个格式化的字符串而不是返回它(给变量)。

哪个更有可读性?

其他回答

我通常使用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时必须小心:

$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有许多用例,但我使用它们的一种方式是在数据库中存储这样的字符串:'Hello, My Name is %s',或将其作为PHP类中的常量。这样当我想要使用该字符串时,我可以简单地这样做:

$name = 'Josh';
// $stringFromDB = 'Hello, My Name is %s';
$greeting = sprintf($stringFromDB, $name);
// $greetting = 'Hello, My Name is Josh'

本质上,它允许在代码中进行一些分离。如果我在代码中的许多地方使用“Hello, My Name is %s”,我可以在一个地方将其更改为“%s是我的名字”,并且它会自动更新其他任何地方,而不必去到每个实例并在连接中移动。

即使我认为同样的事情,除非我最近使用它。当您根据用户输入生成文档时,这将很方便。

"<p>Some big paragraph ".$a["name"]." again have tot ake care of space and stuff .". $a["age"]. "also would be hard to keep track of punctuations and stuff in a really ".$a["token"]. paragarapoh.";

WHich可以很容易地写成

sprintf("Some big paragraph %s. Again have to take care of space and stuff.%s also wouldnt be hard to keep track of punctuations and stuff in a really %s paragraph",$a,$b,$c);

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

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

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

只需文件 (EN_US):

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

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

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