PHP printf() 函数
实例
输出格式化的字符串:
<?php $number = 9; $str = "北京"; printf("在%s有 䍏自行车。",$str,$number); ?>
定义和用法
printf() 函数输出格式化的字符串。
arg1、arg2、arg++ 参数将被插入到主字符串中的百分号(%)符号处。该函数是逐步执行的。在第一个 % 符号处,插入 arg1,在第二个 % 符号处,插入 arg2,依此类推。
Comment:如果 % 符号多于 arg 参数,则您必须使用占位符。占位符被插入到 % 符号之后,由数字和 "\$" 组成。请参见例子 2。
提示:相关函数:sprintf()、 vprintf()、 vsprintf()、 fprintf() 和 vfprintf()
语法
printf(format,arg1,arg2,arg++)
参数 | 描述 |
---|---|
format |
必需。规定字符串以及如何格式化其中的变量。 可能的格式值:
附加的格式值。必需放置在 % 和字母之间(例如 %.2f):
Comment:If multiple of the above format values are used, they must be used in the order listed above and cannot be disrupted. |
arg1 | Required. Specifies the argument to be inserted format The parameter at the first % symbol in the string. |
arg2 | Required. Specifies the argument to be inserted format The parameter at the second % symbol in the string. |
arg++ | Optional. Specifies the argument to be inserted format The parameters at the third, fourth, etc. % symbols in the string. |
Technical details
Return value: | Returns the length of the output string. |
PHP version: | 4+ |
More examples
Example 1
Using format value %f:
<?php $number = 123; printf("%f",$number); ?>
Example 2
Using placeholders:
<?php $number = 123; printf("With two decimal places:%1\$.2f<br>No decimal:%1\$u",$number); ?>
Example 3
Demonstration of all possible format values:
<?php $num1 = 123456789; $num2 = -123456789; $char = 50; // ASCII character 50 is 2 // Comment: The format value "%%" returns a percent sign printf("%%b = %b <br>",$num1); // Binary number printf("%%c = %c <br>",$char); // ASCII character printf("%%d = %d <br>",$num1); // Signed decimal number printf("%%d = %d <br>",$num2); // Signed decimal number printf("%%e = %e <br>",$num1); // Scientific notation (lowercase) printf("%%E = %E <br>",$num1); // Scientific notation (uppercase) printf("%鑾u <br>",$num1); // Unsigned decimal number (positive) printf("%鑾u <br>",$num2); // Unsigned decimal number (negative) printf("%%f = %f <br>",$num1); // Floating-point number (respecting local settings) printf("%%F = %F <br>",$num1); // Floating-point number (not respecting local settings) printf("%%g = %g <br>",$num1); // Shorter than %e and %f printf("%%G = %G <br>", $num1); // Più corto di %E e %f printf("%%o = %o <br>", $num1); // Numero ottale printf("%%s = %s <br>", $num1); // Stringa printf("%%x = %x <br>", $num1); // Numero esadecimale (minuscolo) printf("%%X = %X <br>", $num1); // Numero esadecimale (maiuscolo) printf("%%+d = %+d <br>", $num1); // Simbolo di segno (positivo) printf("%%+d = %+d <br>", $num2); // Simbolo di segno (negativo) ?>
Esempio 4
Dimostrazione dei simboli di stringa:
<?php $str1 = "Hello"; $str2 = "Hello world!"; printf("[%s]<br>", $str1); printf("[%8s]<br>", $str1); printf("[%-8s]<br>", $str1); printf("[%08s]<br>", $str1); printf("[%'*8s]<br>", $str1); printf("[%8.8s]<br>", $str2); ?>