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

例如,在处理输入变量时,可以通过提前指定预期格式(例如,您期望字符串[%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(),但它输出一个格式化的字符串而不是返回它(给变量)。

哪个更有可读性?

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

在PHP手册中有很多例子

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

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

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

如前所述,它允许格式化输入数据。例如,强制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插入攻击。如果你解析未经处理的输入,你的网站和服务器就会被黑客攻击。(当然,那些完全由你的代码构造并保证安全的变量除外。)

使用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
define('TEXT_MESSAGE', 'The variable "%s" is in the middle!');

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