我试图了解更多关于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;

我是不是遗漏了什么?


当前回答

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

"<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);

其他回答

Sprintf具有原始printf的所有格式化功能,这意味着除了在字符串中插入变量值外,您还可以做更多的事情。

例如,指定数字格式(十六进制,十进制,八进制),小数的数量,填充等等。谷歌用于printf,你会找到很多例子。你应该从维基百科上关于printf的文章开始。

如前所述,它允许格式化输入数据。例如,强制2dp, 4位数字等。它对于构建MySQL查询字符串非常有用。

另一个优点是,它允许将字符串的布局与输入的数据分开,就像输入参数一样。例如,在MySQL查询的情况下:

// For security, you MUST sanitise ALL user input first, eg:
$username = mysql_real_escape_string($_POST['username']); // etc.
// Now creating the query:
$query = sprintf("INSERT INTO `Users` SET `user`='%s',`password`='%s',`realname`='%s';", $username, $passwd_hash, $realname);

当然,这种方法还有其他用途,比如将输出打印为HTML等。

编辑:出于安全原因,当使用上述技术时,必须在使用此方法之前使用mysql_real_escape_string()清除所有输入变量,以防止MySQL插入攻击。如果你解析未经处理的输入,你的网站和服务器就会被黑客攻击。(当然,那些完全由你的代码构造并保证安全的变量除外。)

这样的:

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

也可以写成:

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

在我看来,这更容易理解,但我可以看到本地化或格式化的用途。

使用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

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

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

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

只需文件 (EN_US):

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

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

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