简体   繁体   English

在php中添加前导0

[英]Adding leading 0 in php

I have我有

  • tutorial 1 how to make this教程 1 如何制作这个
  • tutorial 21 how to make this教程 21 如何制作这个
  • tutorial 2 how to make this教程 2 如何制作这个
  • tutorial 3 how to make this教程 3 如何制作这个

and i need我需要

  • tutorial 01 how to make this教程 01 如何制作这个
  • tutorial 21 how to make this教程 21 如何制作这个
  • tutorial 02 how to make this教程 02 如何制作这个
  • tutorial 03 how to make this教程 03 如何制作这个

so i can order them properly.所以我可以正确地订购它们。 (adding leading 0 when single digit is found) (找到单个数字时添加前导 0)

What would be a php method to convert?什么是转换的php方法?

thanks in advance提前致谢

note-please make sure that it identifies the single digit numbers only first and then add the leading zero注意 - 请确保它首先识别单个数字,然后添加前导零

str_pad()

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

sprintf()

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

If it is coming from a DB, this is the way to do it on a sql query: 如果它来自数据库,这是在sql查询上执行此操作的方法:

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

This is will get the max value in the table and place the leading zeros. 这将获得表中的最大值并放置前导零。

If it's hardcoded (PHP), use str_pad() 如果是硬编码(PHP),请使用str_pad()

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

This is a small example of what I did on a online php compiler, and it works... 这是我在在线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;

If your goal is to do natural ordering, the way a human being would, why not just use strnatcmp如果您的目标是按照人类的方式进行自然排序,为什么不直接使用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);

The above example will output:上面的示例将输出:

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