Add leading zero if number is under 10 in PHP

965 Views Asked by At

I would like to create a pagination with leading zeros, if the number is under 10: < 07 08 09 10 11 >

My pagination outputs similar HTML:

<div>
    <a href="#">&lt;</a>
    <span>7</span>
    <a href="#">8</a>
    <a href="#">9</a>
    <a href="#">10</a>
    <a href="#">11</a>
    <a href="#">&gt;</a>
</div>

I am trying to use the preg_replace function to catch single digits and to add the leading zero, but I don't know how could I keep the digit:

$r = preg_replace('/>[0-9]</', '>01<', $r);
return $r;

I solved the problem with str_replace but this is ugly:

$r = str_replace(array('>1<','>2<','>3<','>4<','>5<','>6<','>7<','>8<','>9<'), array('>01<','>02<','>03<','>04<','>05<','>06<','>07<','>08<','>09<'), $r);
2

There are 2 best solutions below

1
On

You need to capture the original number and copy it into the replacement.

$r = preg_replace('/>([0-9])</', '>0$1<', $r);

That said, it's generally a bad idea to use regular expressions to process HTML. You should use a proper parser such as DOMDocument.

Or generate the numbers with leading zeroes when creating the HTML in the first place, using sprintf() or str_pad().

1
On

Yes, you can achieve it using sprintf

$numPadded = sprintf("%02d", $num);
echo $numPadded;