问题描述
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 在单个数字前添加前导零,即时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)