Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Changing Phone Number Format with Regex

Tags:

regex

replace

php

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

like image 286
BuddyJoe Avatar asked Jun 15 '11 19:06

BuddyJoe


2 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.

like image 88
James C Avatar answered Nov 09 '22 06:11

James C


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

like image 36
jjmontes Avatar answered Nov 09 '22 07:11

jjmontes