繁体   English   中英

在php中添加前导0

[英]Adding leading 0 in php

我有

  • 教程 1 如何制作这个
  • 教程 21 如何制作这个
  • 教程 2 如何制作这个
  • 教程 3 如何制作这个

我需要

  • 教程 01 如何制作这个
  • 教程 21 如何制作这个
  • 教程 02 如何制作这个
  • 教程 03 如何制作这个

所以我可以正确地订购它们。 (找到单个数字时添加前导 0)

什么是转换的php方法?

提前致谢

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

str_pad()

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

sprintf()

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

如果它来自数据库,这是在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;

如果您的目标是按照人类的方式进行自然排序,为什么不直接使用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
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM