7

I'm trying to figure out how to convert a phone number in the format
+18761234567
into
876-123-4567
using a replace Regex.

5
  • This could be done without regex (just using strstr() if the format is always xxx-xxx-xxxx Commented Jun 15, 2011 at 19:26
  • @andyb if you benchmark the preg_replace() against calling substr() three times you'll find preg_replace() is faster Commented Jun 15, 2011 at 19:34
  • @James C I'm sure it is, however performance wasn't a requirement and the OP might only be doing this once and if so I believe that regex is overkill. I'm not disagreeing that your solution is more elegant and performant though! Commented Jun 15, 2011 at 19:39
  • @andyb "regex" was a requirement though ;) Commented Jun 15, 2011 at 19:40
  • 1
    @James C haha, yes indeed it was - point taken! However I am always mindful of Regular Expressions: Now You Have Two Problems Commented Jun 15, 2011 at 19:43

4 Answers 4

20

I think this should work

preg_replace('/^\+1(\d{3})(\d{3})(\d{4})$/i', '$1-$2-$3', '+18761234567');

I'm assuming that the +1 is constant and then use the \d shortcut to match decimal characters. The value in {} is the number of characters to match.

Sign up to request clarification or add additional context in comments.

1 Comment

Very good regex, because it won't break numbers outside of the North American numbering system.
1

Also, there is a Regexp Library on the Internet. It may be of help.

Search for 'phone':

http://www.regexlib.com/Search.aspx?k=phone&c=-1&m=-1&ps=20

1 Comment

Link corrected. Next time remember you can try to find the site and suggest an edit, instead of downvoting ;-).
0

I know it's not regex but this also works :-)

$num = '+18761234567';
$formatted = substr($num, 2, 3).'-'.substr($num, 5, 3).'-'.substr($num, 8);

Comments

-2

This assumes there are 2 characters a the beginning to ignore.

preg_replace("/([0-9a-zA-Z+]{2})([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "$2-$3-$4", '+18761234567');

2 Comments

it's not right to match on a-zA-Z too. You won't find those characters in a phone number!
Actually it could if it was a vanity number. For example 877-Call-Today

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.