[英]Adding leading 0 in php
我有
我需要
所以我可以正確地訂購它們。 (找到單個數字時添加前導 0)
什么是轉換的php方法?
提前致謝
注意 - 請確保它首先識別單個數字,然后添加前導零
如果它來自數據庫,這是在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.