开发者

How to make a single/double legthed string to minmum of five character legthed in php?

For my site, I need to do the following

$value = "1|22";    
$explode = explode("|",$value);    
$a = $explode[0];    
$b = $explode[1]; 

This will return a and b as 1 and 22 as expected. But I need them to return $a as 00001 and $b as 00022. So if they contain less than 5 characters, I want to add 0 as prefix to it to make it a five-digit number. How c开发者_运维知识库an I do that?


$a = str_pad($explode[0], 5, '0');
$b = str_pad($explode[1], 5, '0');

With PHP5.3 you can prepend the 0 like this

$explode = array_map (function ($entry) {
    return str_pad($entry, 5, '0');
}, $explode);

and assigning

list($a, $b) = $explode;

At all (still php5.3)

list($a, $b) = array_map (function ($entry) {
    return str_pad($entry, 5, '0');
}, explode('|', $value));


Another method.

$value = "1|22";    
$explode = explode("|",$value);    
$a = sprintf( '%1$05d', $explode[0] );    
$b = sprintf( '%1$05d', $explode[1] );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜