我试图了解更多关于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()函数而不是普通连接的优点是,您可以对要连接的变量应用不同类型的格式。

在你的情况下,你做到了

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

and

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

让我们输入$result = 'passed';日期= '23 ';

使用普通的连接,你只能得到输出:

Here is the result: passed for this date 23rd

然而,如果你使用sprintf(),你可以得到一个修改后的输出,如:

$output = sprintf('Here is the result: %.4s for this date %.2s',$result,$date);
echo $output;

输出:

Here is the result: pass for this date 23

其他回答

如果您使用过C/ c++,那么您应该已经习惯了sprintf函数。 很有可能第二条线的效率较低。Echo被设计为输出命令,而sprintf被设计为执行字符串令牌替换。我不是PHP专家,但我怀疑回声涉及到更多的对象。如果它像Java那样工作,那么每当有东西添加到列表中时,它都会创建一个新的字符串,因此最终会创建4个字符串。

define('TEXT_MESSAGE', 'The variable "%s" is in the middle!');

sprintf(TEXT_MESSAGE, "Var1");
sprintf(TEXT_MESSAGE, "Var2");
sprintf(TEXT_MESSAGE, "Var3");

我通常使用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的一个非常好的用例是输出填充格式的数字,以及在字符串中混合不同类型的数字。在许多情况下,它更容易阅读,并且可以超级简单地打印同一变量的不同表示形式,特别是数值形式。

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

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

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

只需文件 (EN_US):

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

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

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