Adding lead 0 in php

I have

  • tutorial 1 how to do it
  • tutorial 21 how to do it
  • tutorial 2 how to do it
  • tutorial 3 how to do it

they do not need

  • tutorial 01 how to do it
  • tutorial 21 how to do it
  • textbook 02 how to do it
  • tutorial 03 how to do it

so I can arrange them correctly. (adding leading 0 when one digit is found)

What will be the php method for conversion?

early

note - make sure that it first identifies only single digits and then adds the leading zero

+6
source share
2 answers

If this comes from a DB, this is the way to do it on sql request:

lpad(yourfield, (select length(max(yourfield)) FROM yourtable),'0') yourfield 

This will get the maximum value in the table and place 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 in the php online 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; 
+4
source

str_pad()

 echo str_pad($input, 2, "0", STR_PAD_LEFT); 

sprintf()

 echo sprintf("%02d", $input); 
+9
source

Source: https://habr.com/ru/post/921355/


All Articles