当前位置: 首页 > 网络学院 > 服务端脚本教程 > PHP > printf() 函数
The printf() function outputs a formatted string.
printf()函数的作用是:输出格式化字符串。
The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This function works "step-by-step". At the first % sign, arg1 is inserted, at the second % sign, arg2 is inserted, etc.
arg1, arg2, ++参数将被插入到主体字符串中的百分号(%)之后。这个函数是“一步一步[step-by-step]”执行的。在第一个“%”之后插入arg1,在第二个“%”之后插入arg2,依次类推。
printf(format,arg1,arg2,arg++) |
Parameter参数 | Description描述 |
---|---|
format | Required. Specifies the string and how to format the variables in it. 必要参数。指定字符串,以及如何定义其中变量的格式。 Possible format values:
Additional format values. These are placed between the % and the letter (example %.2f):
Note: If multiple additional format values are used, they must be in the same order as above. |
arg1 | Required. The argument to be inserted at the first %-sign in the format string 必要参数。这个自变量(arg1)必须安插在第一个%-符号前 |
arg2 | Optional. The argument to be inserted at the second %-sign in the format string 可选参数。这个自变量(arg2)必须安插在第二个%-符号前 |
arg++ | Optional. The argument to be inserted at the third, fourth, etc. %-sign in the format string 可选参数。与上述自变量相同,它们可以安插在第三个、第四个……(依次类推)%-符号前。 |
Note: If there are more % signs than arguments, you must use placeholders. A placeholder is inserted after the % sign, and consists of the argument- number and "$". See example three.
注意:注意:如果这里的%比自变量更多,你必须使用占位符[placeholders]。占位符是安插在%之后的,它是由自变量-数字和“$”组成的。具体可以见案例3。
Tip: Related functions: fprintf(), sprintf(), vfprintf(), vprintf(), and vsprintf().
提示:相关函数:printf(), sprintf(), vfprintf(), vprintf(), 和 vsprintf()
<?php $str = "Hello"; $number = 123; printf("%s world. Day number %u",$str,$number); ?> |
The output of the code above will be:
上述代码将输出下面的结果:
Hello world. Day number 123 |
<?php $number = 123; printf("%f",$number); ?> |
The output of the code above will be:
上述代码将输出下面的结果:
123.000000 |
Use of placeholders:
使用占位符
<?php $number = 123; printf("With 2 decimals: %1$.2f <br />With no decimals: %1$u",$number); ?> |
The output of the code above will be:
上述代码将输出下面的结果:
With 2 decimals: 123.00 With no decimals: 123 |