PHP 中的符号说明符和填充说明符如何与 printf() 和 sprintf() 一起使用?

问题描述 投票:0回答:4

我正在学习 printf,sprintf,我不明白一些要点,如果有人可以帮助我理解这些要点,

在此链接PHP 手册

有解释从一到六:

我不明白的是:第一个和第二个(1(符号说明符),2(填充说明符)),如果有人可以帮我举例,我将非常感激。

php printf
4个回答
30
投票

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

以下两者相等:

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

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

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*****
© www.soinside.com 2019 - 2024. All rights reserved.