问题描述
|
这个问题已经在这里有了答案:
解决方法
您可以使用sprintf:http://php.net/manual/en/function.sprintf.php
<?php
$num = 4;
$num_padded = sprintf(\"%02d\",$num);
echo $num_padded; // returns 04
?>
如果小于所需的字符数,则只会添加零。
编辑:@FelipeAls指出:
使用数字时,应使用%d
(而不是%s
),尤其是当有可能出现负数时。如果您只使用正数,则两种方法都可以正常工作。
例如:
sprintf(\"%04s\",10);
返回0010
sprintf(\"%04s\",-10);
返回0-10
如:
sprintf(\"%04d\",10);
返回0010
sprintf(\"%04d\",-10);
返回-010
,您可以使用ѭ7来加0
str_pad($month,2,\'0\',STR_PAD_LEFT);
string str_pad ( string $input,int $pad_length [,string $pad_string = \" \" [,int $pad_type = STR_PAD_RIGHT ]] )
,字符串格式化通用工具,sprintf
:
$stamp = sprintf(\'%s%02s\',$year,$month);
http://php.net/manual/zh/function.sprintf.php