在 PHP 中添加前导零

7

我有以下教程:

  • tutorial 1 如何制作这个
  • tutorial 21 如何制作这个
  • tutorial 2 如何制作这个
  • tutorial 3 如何制作这个

我需要:

  • tutorial 01 如何制作这个
  • tutorial 21 如何制作这个
  • tutorial 02 如何制作这个
  • tutorial 03 如何制作这个

这样我就可以正确排序(在单个数字前添加前导0)。

请问有什么PHP方法可以实现转换吗?

谢谢提前。

注意:请确保首先识别单个数字,然后再添加前导零。


sprintf - Musa
三位数呢?当你达到100个教程时,你想让01变成001吗?四位数呢?等等。 - Peter
现在,两位数字就足够了,我看不出教程超过100的情况,谢谢。 - msjsam
3个回答

11

str_pad()

echo str_pad($input, 2, "0", STR_PAD_LEFT);

sprintf()

echo sprintf("%02d", $input);

这个程序没有识别“仅限单个数字”的条件,请帮忙。 - msjsam

4

如果数据来自数据库,这是使用SQL查询语句的方法:

lpad(yourfield, (select length(max(yourfield)) FROM yourtable),'0') yourfield

这将获取表格中的最大值并放置前导零。

如果是硬编码(PHP),请使用 str_pad()。

str_pad($yourvar, $numberofzeros, "0", STR_PAD_LEFT);

这是我在一个在线php编译器上完成的小例子,它可以正常运行...

$string = "Tutorial 1 how to";

$number = explode(" ", $string); //Divides the string in a array
$number = $number[1]; //The number is in the position 1 in the array, so this will be number variable

$str = ""; //The final number
if($number<10) $str .= "0"; //If the number is below 10, it will add a leading zero
$str .= $number; //Then, add the number

$string = str_replace($number, $str, $string); //Then, replace the old number with the new one on the string

echo $string;

0
如果您的目标是进行自然排序,就像人类一样,为什么不直接使用strnatcmp呢?
$arr = [
    'tutorial 1 how to make this',
    'tutorial 21 how to make this',
    'tutorial 2 how to make this',
    'tutorial 3 how to make this',
];
usort($arr, "strnatcmp");
print_r($arr);

上面的例子将输出:

Array
(
    [0] => tutorial 1 how to make this
    [1] => tutorial 2 how to make this
    [2] => tutorial 3 how to make this
    [3] => tutorial 21 how to make this
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接