regular expression to remove space ONLy between numbers

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
yacahuma
Forum Regular
Posts: 870
Joined: Sun Jul 01, 2007 7:11 am

regular expression to remove space ONLy between numbers

Post by yacahuma »

need regular expression to remove space ONLy between numbers
so
John Doe (dont remove space)

but
1 2 3 4 5 should be 12345
333 444 5555 should be 3334445555


thank you
I tried

Code: Select all

 
 preg_replace('/(\d)+[\s](\d)+/',"$1$2", $v);
 
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: regular expression to remove space ONLy between numbers

Post by prometheuzz »

Use look-arounds for this:

Code: Select all

echo preg_replace('/(?<=\d)\s+(?=\d)/',"", 'abc 1 2 3 4 def');
User avatar
yacahuma
Forum Regular
Posts: 870
Joined: Sun Jul 01, 2007 7:11 am

Re: regular expression to remove space ONLy between numbers

Post by yacahuma »

Thank you , exactly what I needed. I always hate not spending time trying to learn regex.
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: regular expression to remove space ONLy between numbers

Post by prometheuzz »

yacahuma wrote:Thank you , exactly what I needed.
No problem.
yacahuma wrote:I always hate not spending time trying to learn regex.
If you'd like to know some more (you seem to grasp the basics well enough), I highly recommend "Mastering Regular Expressions" by J. Friedl: THE book if it comes to regular expressions.

Also, if you're not quite sure why

Code: Select all

'/(?<=\d)\s+(?=\d)/' // replace with ''
works, but

Code: Select all

'/(\d)\s+(\d)/' // replace with '$1$2'
doesn't, feel free to ask and I'll explain it to you.
Post Reply