views:

150

answers:

2

I need a little help here. This code correctly displays every format I enter--except when it's xxx.xxx.xxxx

It keeps the periods in! How do I filter out periods too?

preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "$1-$2-$3", $phone_enter)
+2  A: 

You need to update the query so it will allow a . (dot), i added the \.? which means, a dot may appear zero or one time.

preg_replace("/([0-9]{3})\.?([0-9]{3})\.?([0-9]{4})/", "$1-$2-$3", $phone_enter)
Am
Yep, escape the dots and keep 'em outside of the groups. I'd upvote but I've hit my limit already...
AJ
there is a daily vote limit?
Am
Yeah, there's a badge for hitting it, I think.
Kevin Brown
+2  A: 

I would do this:

preg_replace('/(\d{3})([.-])?(\d{3})\2(\d{4})/', '$1-$3-$4', $phone_number);

\d is shorthand for [0-9]. The use of the backreference means you can enter "123.456.7890" or "123.456.7890" but not "123.4567890" or "123.456-7890".

Also bear in mind that other countries have different phone number formats, if that's relevant to what you're doing.

cletus
@cletus, the _\2_ means the second group again?
Am
@Am: yes, that's the backreference. See http://www.regular-expressions.info/brackets.html
cletus