本文介绍了在PHP中添加前导0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
- 教程1如何制作这个
- 教程21
- 教程2如何制作
- 教程3如何制作
我需要
- 教程01如何制作这个
- 教程21如何制作这个
- 教程02如何制作这个
- 教程03如何制作这个
所以我可以正确地订购它们。 (在找到单个数字时加上前导0)
什么是php方法转换?
谢谢请注意,请确保它只识别单个数字的数字,然后添加前导零
如果它来自一个数据库,这是一个SQL查询的方式:
lpad(yourfield,(select length(max(yourfield))FROM yourtable),'0')yourfield
如果是硬编码(PHP),请使用str_pad()
这将获得表中的最大值并放置前导零。 / p>
str_pad($ yourvar,$ numberofzeros,0,STR_PAD_LEFT);
这是我在在线php编译器上做的一个小例子,它可以工作。
$ string =教程1如何;
$ number = explode(,$ string); //将字符串分成一个数组
$ number = $ number [1]; //数字在数组中的位置1,所以这将是数字变量
$ str =; //最后一个数字
if($ number <10)$ str。=0; //如果数字小于10,则会添加前导零
$ str。= $ number; //然后,添加数字
$ string = str_replace($ number,$ str,$ string); //然后,用字符串
中的新数字替换旧数字echo $ string;
I have
- tutorial 1 how to make this
- tutorial 21 how to make this
- tutorial 2 how to make this
- tutorial 3 how to make this
and i need
- tutorial 01 how to make this
- tutorial 21 how to make this
- tutorial 02 how to make this
- tutorial 03 how to make this
so i can order them properly. (adding leading 0 when single digit is found)
What would be a php method to convert?
thanks in advance
note-please make sure that it identifies the single digit numbers only first and then add the leading zero
解决方案
If it is coming from a DB, this is the way to do it on a sql query:
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()
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...
$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;
这篇关于在PHP中添加前导0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!