PHP prepend leading zero before single digit number, on-the-fly(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);
返回 0010sprintf("%04s", -10);
返回 0-10
sprintf("%04s", 10);
returns 0010
sprintf("%04s", -10);
returns 0-10
在哪里:
sprintf("%04d", 10);
返回 0010sprintf("%04d", -10);
返回 -010
sprintf("%04d", 10);
returns 0010
sprintf("%04d", -10);
returns -010
这篇关于PHP 在单个数字前添加前导零,即时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP 在单个数字前添加前导零,即时


- Mod使用GET变量将子域重写为PHP 2021-01-01
- Laravel 仓库 2022-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01