0

I have large strings that contain dates, single digit numbers and double digit numbers. I need to find and pad the single digit numbers (which could also be in the dates, as the months and days can possibly be single digits) with a preceding zero. The data is in this format:

m/d/yyyy 1,21,3,42,5,63,7,84,9

I need it in this format

mm/dd/yyyy 01,21,03,42,05,63,07,84,09

I've tried this:

$pattern = "#[9]{1}#m";
$str = preg_replace($pattern, "09, $str);

It kind of works, but for numbers like 29 that shouldn't be touched, it turns it into 209. Ideally I'd like to use a wildcard instead of a specific number so that it'll just pad all of the single digit numbers in the string but I haven't quite figured that part out. Any and all help would be appreciated , thanks.

Steve
  • 11
  • 3

1 Answers1

1

You can match a digit 1-9 not surrounded by digits

(?<!\d)[1-9](?!\d)

Regex demo

Replace with a zero and the full match 0$0

If you don't want to match the digits in the date, you can assert a comma or the end of the string to the right:

\b[1-9](?=,|$)

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • @Steve The first one or the second one? Did you see my question in the comments? – The fourth bird Oct 07 '21 at 20:59
  • 1
    The first one worked for me. As for your questions above, I won't have single or double zeros to worry about in the strings, as for the #1#, I think this means if I need to pad with a 1 instead, that won't happen with my data, I only needed the zeros. Thanks again – Steve Oct 07 '21 at 22:02