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 在单个数字前添加前导零,即时
基础教程推荐
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01