以 % 符号开头的 printf 或 sprintf 字符是占位符(或标记)。它们将被作为参数传递的变量替换。
示例:
$str1 = 'best';
$str2 = 'world';
$say = sprintf('Tivie is the %s in the %s!', $str1, $str2);
echo $say;
这将输出:
Tivie 是世界上最好的!
注意:还有更多的占位符(%s 表示字符串,%d 表示十进制数等...)
订单:
传递参数的顺序很重要。如果您将 $str1 与 $str2 切换为
$say = sprintf('Tivie is the %s in the %s!', $str2, $str1);
它会打印出来
“Tivie 是世界上最好的!”
但是,您可以像这样更改参数的阅读顺序:
$say = sprintf('Tivie is the %2$s in the %1$s!', $str2, $str1);
这将正确打印句子。
另外,请记住 PHP 是一种动态语言,不需要(或支持)显式类型定义。这意味着它会根据需要处理变量类型。在 sprint 中,这意味着如果您将“字符串”作为数字占位符 (%d) 的参数传递,该字符串将被转换为可能产生奇怪结果的数字 (int, float...)。这是一个例子:
$onevar = 2;
$anothervar = 'pocket';
$say = sprintf('I have %d chocolate(s) in my %d.', $onevar, $anothervar);
echo $say;
这将打印出来
我的 0 中有 2 块巧克力。
更多阅读PHPdocs