首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在PHP中格式化电话号码

在PHP中格式化电话号码
EN

Stack Overflow用户
提问于 2011-01-17 05:40:27
回答 22查看 223.3K关注 0票数 113

我在一个短信应用程序上工作,需要能够将发送者的电话号码从+11234567890转换到1234567890,以便它可以与MySQL数据库中的记录进行比较。

数字以后一种格式存储,以便在网站上的其他地方使用,我不愿更改这种格式,因为这将需要修改大量代码。

我该如何使用

谢谢!

EN

回答 22

Stack Overflow用户

回答已采纳

发布于 2011-01-17 05:52:27

代码语言:javascript
复制
$data = '+11234567890';

if(  preg_match( '/^\+\d(\d{3})(\d{3})(\d{4})$/', $data,  $matches ) )
{
    $result = $matches[1] . '-' .$matches[2] . '-' . $matches[3];
    return $result;
}
票数 113
EN

Stack Overflow用户

发布于 2012-05-25 00:22:18

这是一个美国电话格式化程序,可以处理比任何当前答案更多版本的数字。

代码语言:javascript
复制
$numbers = explode("\n", '(111) 222-3333
((111) 222-3333
1112223333
111 222-3333
111-222-3333
(111)2223333
+11234567890
    1-8002353551
    123-456-7890   -Hello!
+1 - 1234567890 
');


foreach($numbers as $number)
{
    print preg_replace('~.*(\d{3})[^\d]{0,7}(\d{3})[^\d]{0,7}(\d{4}).*~', '($1) $2-$3', $number). "\n";
}

下面是正则表达式的细目:

代码语言:javascript
复制
Cell: +1 999-(555 0001)

.*          zero or more of anything "Cell: +1 "
(\d{3})     three digits "999"
[^\d]{0,7}  zero or up to 7 of something not a digit "-("
(\d{3})     three digits "555"
[^\d]{0,7}  zero or up to 7 of something not a digit " "
(\d{4})     four digits "0001"
.*          zero or more of anything ")"

更新: 2015年3月11日,使用{0,7}代替{,7}

票数 170
EN

Stack Overflow用户

发布于 2013-01-05 08:33:02

此功能将设置国际(10+数字)、非国际(10位)或旧学校(7位)电话号码的格式。除10+、10位或7位以外的任何数字都将保持无格式。

代码语言:javascript
复制
function formatPhoneNumber($phoneNumber) {
    $phoneNumber = preg_replace('/[^0-9]/','',$phoneNumber);

    if(strlen($phoneNumber) > 10) {
        $countryCode = substr($phoneNumber, 0, strlen($phoneNumber)-10);
        $areaCode = substr($phoneNumber, -10, 3);
        $nextThree = substr($phoneNumber, -7, 3);
        $lastFour = substr($phoneNumber, -4, 4);

        $phoneNumber = '+'.$countryCode.' ('.$areaCode.') '.$nextThree.'-'.$lastFour;
    }
    else if(strlen($phoneNumber) == 10) {
        $areaCode = substr($phoneNumber, 0, 3);
        $nextThree = substr($phoneNumber, 3, 3);
        $lastFour = substr($phoneNumber, 6, 4);

        $phoneNumber = '('.$areaCode.') '.$nextThree.'-'.$lastFour;
    }
    else if(strlen($phoneNumber) == 7) {
        $nextThree = substr($phoneNumber, 0, 3);
        $lastFour = substr($phoneNumber, 3, 4);

        $phoneNumber = $nextThree.'-'.$lastFour;
    }

    return $phoneNumber;
}
票数 61
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4708248

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档