简体   繁体   English

PHP - 使用正则表达式更改电话号码格式

[英]PHP - Changing Phone Number Format with Regex

I'm trying to figure out how to convert a phone number in the format 我正在试图弄清楚如何转换格式的电话号码
+18761234567 18761234567
into
876-123-4567 876-123-4567
using a replace Regex. 使用替换正则表达式。

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. 我假设+1是常量,然后使用\\d快捷方式匹配小数字符。 The value in {} is the number of characters to match. {}中的值是要匹配的字符数。

Also, there is a Regexp Library on the Internet. 此外,Internet上还有一个Regexp Library。 It may be of help. 它可能会有所帮助。

Search for 'phone': 搜索“手机”:

http://www.regexlib.com/Search.aspx?k=phone&c=-1&m=-1&ps=20 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);

这假设开头要忽略2个字符。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM