-3

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);
István
  • 127
  • 10
  • @aynber That question doesn't show how to do when the number is being replaced with `preg_replace()`. – Barmar Apr 15 '21 at 16:10
  • @Barmar Ah, I didn't realize the OP was trying to do it after the HTML was generated. – aynber Apr 15 '21 at 16:13
  • 1
    It would be best to do this when generating the HTML in the first place, rather than fix it up later. – Barmar Apr 15 '21 at 16:16
  • I am using a built in function to display the pagination so I have to modify the HTML output – István Apr 15 '21 at 16:52

2 Answers2

5

Yes, you can achieve it using sprintf

$numPadded = sprintf("%02d", $num);
echo $numPadded; 
dev_mustafa
  • 1,042
  • 1
  • 4
  • 14
  • Show how to do that in the `preg_replace()`. You'll need to use `preg_replace_callback()`, which seems like overkill for this. – Barmar Apr 15 '21 at 16:16
2

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().

Barmar
  • 741,623
  • 53
  • 500
  • 612