Home > Mobile >  How to find single digits in a large string with regex php [duplicate]
How to find single digits in a large string with regex php [duplicate]

Time:10-08

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.

CodePudding user response:

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

  • Related