PHP,Printf,Sprintf函数

3

我正在学习printf、sprintf相关内容,但是有几个点我不太理解,希望有人可以帮我解答。

在这个链接PHP手册中:

有六个解释:

我不明白的是:第一和第二(1(标志说明符),2(填充说明符)),如果有人能举例说明一下,我将非常感激。


2
那个文档页面上有很多很多的例子。你也可以自己尝试一下! - Oliver Charlesworth
4个回答

30

sprintf()返回一个字符串,printf()显示它。

以下两个是相等的:

printf(currentDateTime());
print sprintf(currentDateTime());

这意味着printf作为标准输出打印。 - Hardik

12

标记说明符强制使用符号,即使它是正数。因此,如果您有

$x = 10;
$y = -10;
printf("%+d", $x);
printf("%+d", $y);

你将得到:

+10
-10

填充格式说明符可以添加左侧填充,以使输出总是占据一组空格,这允许您对齐数字堆栈,在生成带有总计等报告时非常有用。

 $x = 1;
 $y = 10;
 $z = 100;
 printf("%3d\n", $x);
 printf("%3d\n", $y);
 printf("%3d\n", $z);

你将会得到:

   1
  10
 100

如果在填充说明符之前加上零,字符串将被零填充而不是空格填充:

 $x = 1;
 $y = 10;
 $z = 100;
 printf("%03d\n", $x);
 printf("%03d\n", $y);
 printf("%03d\n", $z);

提供:

 001
 010
 100

如果填充参数为空格,则浏览器不会显示填充。只有在给定某个字符作为参数时,填充才会被显示。 - rancho
当然可以。这是针对文本输出,而不是 HTML。如果您需要 HTML,则使用 CSS 进行对齐。或将其包装在 PRE 标记中。 - Alex Howansky
这是正确的。sprintf()返回一个字符串,printf()显示它。 - shihab mm

2
符号说明符:在数值前加上加号(+),可以强制显示正负号(默认情况下只有负数有符号)。
$n = 1;

$format = 'With sign %+d  without %d';
printf($format, $n, $n);

打印:

带符号+1,无符号1

填充说明符指定用于将结果填充到指定长度的字符。该字符通过在其前面加上单引号(')来指定。例如,要使用字符'a'填充到长度为3:

$n = 1;

$format = "Padded with 'a' %'a3d"; printf($format, $n, $n);
printf($format, $n, $n);

打印:

使用'a'进行填充 aa1


0

1.符号说明符:

默认情况下,浏览器只会在负数前显示-符号。正数前的+符号被省略。但是可以通过使用符号说明符来指示浏览器在正数前显示+符号。例如:

$num1=10;
$num2=-10;
$output=sprintf("%d",$num1);
echo "$output<br>";
$output=sprintf("%d",$num2);
echo "$output";

输出:

10
-10

这里省略了正数前面的+符号。但是,如果我们在%d%字符后面放置一个+符号,则不再省略。

$num1=10;
$num2=-10;
$output=sprintf("%+d",$num1);
echo "$output<br>";
$output=sprintf("%+d",$num2);
echo "$output";

输出:

+10
-10

2.填充说明符:

填充说明符可以在输出的左侧或右侧添加指定数量的字符。这些字符可以是空格、零或任何其他ASCII字符。

例如:

$str="hello";
$output=sprintf("[%10s]",$str);
echo $output;

源代码输出:

[     hello]             //Total length of 10 positions,first five being empty spaces and remaining five being "hello"

HTML 输出:

 [ hello]                 //HTML displays only one empty space and collapses the rest, you have to use the <pre>...</pre> tag in the code for HTML to preserve the empty spaces.

在左侧放置负号将输出左对齐:

$output=["%-10s",$string];
echo $output;

源代码输出:

[hello     ]

HTML 输出:

[hello ]

在编程中,将%符号后面加上0可以用零替换空格。

$str="hello";
$output=sprintf("[%010s]",$str);
echo $output;

输出:

[00000hello]

左对齐

$output=sprintf("[%-010s]",$str);

输出:

[hello00000]

% 后面加上任何 ASCII 字符,如 *,会导致显示该 ASCII 字符而不是空格。

$str="hello";
$output=sprintf("[%'*10s]",$str);
echo $output;

输出:

*****hello

左对齐:

$output=sprintf("[%-'*10s]",$str);
echo $output;

输出:

hello*****

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接