簡體   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