php 字符串中的零填充数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/324358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:23:52  来源:igfitidea点击:

Zero-pad digits in string

phpzero-pad

提问by Konrad Rudolph

I need to cast single figures (1 to 9) to (01 to 09). I can think of a way but its big and ugly and cumbersome. I'm sure there must be some concise way. Any Suggestions

我需要将单个数字(1 到 9)转换为(01 到 09)。我能想到一种方法,但它又大又丑又笨重。我确定必须有一些简洁的方法。有什么建议

回答by Konrad Rudolph

First of all, your description is misleading. Doubleis a floating point data type. You presumably want to pad your digits with leading zeros in a string. The following code does that:

首先,你的描述有误导性。Double是浮点数据类型。您大概想用字符串中的前导零填充数字。以下代码执行此操作:

$s = sprintf('%02d', $digit);

For more information, refer to the documentation of sprintf.

有关更多信息,请参阅sprintf.

回答by LeppyR64

There's also str_pad

还有str_pad

<?php
$input = "Alien";
echo str_pad($input, 10);                      // produces "Alien     "
echo str_pad($input, 10, "-=", STR_PAD_LEFT);  // produces "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH);   // produces "__Alien___"
echo str_pad($input, 6 , "___");               // produces "Alien_"
?>

回答by Alex

Solution using str_pad:

使用str_pad 的解决方案:

str_pad($digit,2,'0',STR_PAD_LEFT);

Benchmark on php 5.3

php 5.3 基准测试

Result str_pad : 0.286863088608

Result sprintf : 0.234171152115

结果 str_pad : 0.286863088608

结果 sprintf : 0.234171152115

Code:

代码:

$start = microtime(true);
for ($i=0;$i<100000;$i++) {
    str_pad(9,2,'0',STR_PAD_LEFT);
    str_pad(15,2,'0',STR_PAD_LEFT);
    str_pad(100,2,'0',STR_PAD_LEFT);
}
$end = microtime(true);
echo "Result str_pad : ",($end-$start),"\n";

$start = microtime(true);
for ($i=0;$i<100000;$i++) {
    sprintf("%02d", 9);
    sprintf("%02d", 15);
    sprintf("%02d", 100);
}
$end = microtime(true);
echo "Result sprintf : ",($end-$start),"\n";