我有过
我需要
这样我就能点好了。(在找到个位数时添加前导0)
要转换的php方法是什么?
提前感谢
注-请确保它只首先识别个位数,然后再添加前导零。
发布于 2012-07-26 00:32:32
如果它来自DB,那么这就是在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;发布于 2012-07-26 00:29:09
str_pad()
echo str_pad($input, 2, "0", STR_PAD_LEFT);sprintf()
echo sprintf("%02d", $input);发布于 2022-01-11 13:01:56
如果你的目标是做自然排序,就像人类一样,为什么不直接使用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
)https://stackoverflow.com/questions/11660683
复制相似问题