首页 PHP 正文
245

php之printf()小析

好吧,把printf()梳理一遍 :
$num = 5; 
$location = "tree"; 
$format = "There are %d monkeys in the %s"; 
printf($format,$num,$location); 
//output:There are 5 monkeys in the tree 
//%d 表示 数字,%s 表示 字符串,注意对应顺序。 

$format = "The %2\$s contains %1\$d monkeys"; 
printf($format,$num,$location); 
//output:There are 5 monkeys in the tree 
//可以指定对应参数的序号。 

$s = 'monkey'; 
$t = 'many monkeys'; 
printf("[%s]",$s);//monkey 
printf("[%10s]",$s);//从字符串右边开始输出10个字符长度,不足的长度用空格补足。[    monkey] 
printf("[%-10s]",$s);//与上相反的方向补齐字符串。[monkey    ] 
printf("[%010s]",$s);//除了上面用空格填充字符串之外,还可以用数字0填充。[0000monkey] 
printf("[%'#10s]",$s);//还可以通过字符前面加单引号来自定义填充字符。[####monkey] 
printf("[%10.10s]",$t);//前面的例子是填充字符串,本例用到小数点与字符串格式符号的组合来截断字符串。正数表示取左边的10个字符长度。 

printf("%04d-%02d-%02d",$year,$month,%day);//04d表示将传入的数字用数字0从左填充到4位长度。 
printf("%01.2f",123.1);//小数点前面的01表示至少要1位,否则用数字0填充;小数点后面的2表示保留两位小数。outputs 123.10 
printf("%.3e",362525200);//outputs 3.63e+8

正在加载评论...