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

我是不是遗漏了什么?


当前回答

一个是“输出”,另一个是“返回”,这是主要的区别之一。

printf()输出

sprintf()返回

其他回答

参数与使用模板的参数相同。您需要将Textsleev与实际的变量值分开。除了我们提到的sprintf的额外功能之外,它只是一个样式问题。

sprintf的另一个用途是在本地化的应用程序中,因为sprintf的参数不必按照它们在格式字符串中出现的顺序排列。

例子:

$color = 'blue';
$item = 'pen';

sprintf('I have a %s %s', $color, $item);

但是像法语这样的语言对单词的顺序是不同的:

$color = 'bleu';
$item = 'stylo';

sprintf('J\'ai un %2$s %1$s', $color, $item);

(是的,我的法语很烂:我在学校学过德语!)

实际上,您可以使用gettext来存储本地化的字符串,但您可以理解。


在循环中使用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()格式化字符串更干净、更安全。

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

哪个更有可读性?

你为什么要用它?

在为语言字符串使用(外部)源时,它被证明非常有用。如果你在一个给定的多语言字符串中需要固定数量的变量,你只需要知道正确的顺序:

en.txt

not_found    = "%s could not be found."
bad_argument = "Bad arguments for function %s."
bad_arg_no   = "Bad argument %d for function %s."

hu.txt

not_found    = "A keresett eljárás (%s) nem található."
bad_argument = "Érvénytelen paraméterek a(z) %s eljárás hívásakor."
bad_arg_no   = "Érvénytelen %d. paraméter a(z) %s eljárás hívásakor."

在多种语言中,插入的变量甚至不必在开头或结尾,只是它们的顺序很重要。

当然,你可以编写自己的函数来执行这个替换,毫无疑问,甚至会有一些小的性能提升,但它要快得多(假设你有一个类Language来读取语言字符串):

/**
 * throws exception with message($name = "ExampleMethod"):
 *  - using en.txt: ExampleMethod could not be found.
 *  - using hu.txt: A keresett eljárás (ExampleMethod) nem található.
 */
throw new Exception(sprintf(Language::Get('not_found'), $name));

/**
 * throws exception with message ($param_index = 3, $name = "ExampleMethod"):
 *  - using en.txt: Bad argument 3 for function ExampleMethod.
 *  - using hu.txt: Érvénytelen 3. paraméter a(z) ExampleMethod eljárás hívásakor.
 */
throw new Exception(sprintf(Language::Get('bad_arg_no'), $param_index, $name));

它还带有printf的全部功能,因此也是格式化多种类型变量的一行程序,例如:

浮点数输出精度,或 用前导零填充整数。