PHP即时在单个数字前加零开头,即时[重复]

问题描述

|                                                                                                                   这个问题已经在这里有了答案:                                                      

解决方法

您可以使用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     

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...