PHP 在一位数之前预先添加前导零,即时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5659042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP prepend leading zero before single digit number, on-the-fly
提问by Ben
PHP - Is there a quick, on-the-fly method to test for a single character string, then prepend a leading zero?
PHP - 是否有一种快速、即时的方法来测试单个字符串,然后在前面加上前导零?
Example:
例子:
$year = 11;
$month = 4;
$stamp = $year.add_single_zero_if_needed($month); // Imaginary function
echo $stamp; // 1104
回答by Kirk Beard
You can use sprintf: http://php.net/manual/en/function.sprintf.php
您可以使用 sprintf:http: //php.net/manual/en/function.sprintf.php
<?php
$num = 4;
$num_padded = sprintf("%02d", $num);
echo $num_padded; // returns 04
?>
It will only add the zero if it's less than the required number of characters.
如果它少于所需的字符数,它只会添加零。
Edit: As pointed out by @FelipeAls:
编辑:正如@FelipeAls 所指出的:
When working with numbers, you should use %d
(rather than %s
), especially when there is the potential for negative numbers. If you're only using positive numbers, either option works fine.
处理数字时,您应该使用%d
(而不是%s
),尤其是在可能出现负数时。如果您只使用正数,则任一选项都可以正常工作。
For example:
例如:
sprintf("%04s", 10);
returns 0010sprintf("%04s", -10);
returns 0-10
sprintf("%04s", 10);
返回 0010sprintf("%04s", -10);
返回 0-10
Where as:
然而:
sprintf("%04d", 10);
returns 0010sprintf("%04d", -10);
returns -010
sprintf("%04d", 10);
返回 0010sprintf("%04d", -10);
返回 -010
回答by Gaurav
You can use str_pad
for adding 0's
您可以str_pad
用于添加 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 ]] )
string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )
回答by deceze
The universal tool for string formatting, sprintf
:
字符串格式化的通用工具,sprintf
:
$stamp = sprintf('%s%02s', $year, $month);