Issue
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.
Solution
You can match a digit 1-9 not surrounded by digits
(?<!\d)[1-9](?!\d)
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](?=,|$)
Answered By - The fourth bird Answer Checked By - David Goodson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.