我有以下教程:
- tutorial 1 如何制作这个
- tutorial 21 如何制作这个
- tutorial 2 如何制作这个
- tutorial 3 如何制作这个
我需要:
- tutorial 01 如何制作这个
- tutorial 21 如何制作这个
- tutorial 02 如何制作这个
- tutorial 03 如何制作这个
这样我就可以正确排序(在单个数字前添加前导0)。
请问有什么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
)