PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] How to find single digits in a large string with regex php

 November 20, 2022     php, preg-replace, regex     No comments   

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)

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



Answered By - The fourth bird
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing