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 在单个数字前添加前导零,即时
基础教程推荐
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何替换eregi() 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
