PHP - change phone number format using regular expression

I am trying to figure out how to convert a phone number to a format
+18761234567
in
876-123-4567
using a Regex replacement.

+6
source share
4 answers

I think this should work

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

I assume +1 is a constant, and then use the \d shortcut to match decimals. The value in {} is the number of characters to match.

+17
source

There is also a Regexp library on the Internet. This may be helpful.

Search for "phone":

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

+1
source

I know this is not a regex, but it also works :-)

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

This suggests that there are two characters - 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
source

Source: https://habr.com/ru/post/890636/


All Articles