开发者

PHP - Changing Phone Number Format with Regex

开发者 https://www.devze.com 2023-03-13 10:53 出处:网络
I\'m trying to figure out how to convert a phone number in the format +18761234567 into 876-123-4567 using a replace Rege开发者_开发技巧x.I think this should work

I'm trying to figure out how to convert a phone number in the format

+18761234567

into

876-123-4567

using a replace Rege开发者_开发技巧x.


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.


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


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

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


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');
0

精彩评论

暂无评论...
验证码 换一张
取 消