PHP 在单个数字前添加前导零,即时

2022-01-17 00:00:00 string numbers zero php

PHP - 是否有一种快速、即时的方法来测试单个字符串,然后在前面加上前导零?

PHP - Is there a quick, on-the-fly method to test for a single character string, then prepend a leading zero?

例子:

$year = 11;
$month = 4;

$stamp = $year.add_single_zero_if_needed($month);  // Imaginary function

echo $stamp; // 1104

推荐答案

你可以使用 sprintf: http://php.net/manual/en/function.sprintf.php

You can use 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.

正如@FelipeAls 指出的那样:

在处理数字时,您应该使用 %d(而不是 %s),尤其是在可能出现负数时.如果您只使用正数,则任一选项都可以正常工作.

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.

例如:

sprintf("%04s", 10); 返回 0010
sprintf("%04s", -10); 返回 0-10

sprintf("%04s", 10); returns 0010
sprintf("%04s", -10); returns 0-10

在哪里:

sprintf("%04d", 10); 返回 0010
sprintf("%04d", -10); 返回 -010

sprintf("%04d", 10); returns 0010
sprintf("%04d", -10); returns -010

相关文章