I'm trying to figure out how to convert a phone number in the format
+18761234567
into
876-123-4567
using a replace Regex.
4 Answers
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.
1 Comment
Terence Johnson
Very good regex, because it won't break numbers outside of the North American numbering system.
Also, there is a Regexp Library on the Internet. It may be of help.
Search for 'phone':
1 Comment
jjmontes
Link corrected. Next time remember you can try to find the site and suggest an edit, instead of downvoting ;-).
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
James C
it's not right to match on a-zA-Z too. You won't find those characters in a phone number!
Jason Small
Actually it could if it was a vanity number. For example 877-Call-Today
preg_replace()against callingsubstr()three times you'll findpreg_replace()is faster