PHP regex vs explode()用于电话号码

时间:2011-10-25 18:02:12

标签: php explode

我一直在弄乱一些正则表达式,我遇到了一个小打嗝,其中包含更复杂的电话号码格式。

以下是我正在使用的内容:

$ number1 ='+ 1(123)1234567'; $ number1 ='+ 966(1)1234567 x555';

这些字符串实际上是从我创建的MySQL查询输出的,我喜欢它。 但是,我正在制作一个简单的php函数来自动格式化订阅者编号从1234567到123-4567。

我不太关心任何不以+1开头的数字。所以我正在格式化美国和加拿大的数字。

这是我尝试的内容,如果只有7位数字,并且字符串以+1开头

<?php

function format_phonenumbers($phone){
    if(empty($phone)){ return ''; }

    $exploded = explode(' ',$phone);

    $countrycode = $exploded[0];
    $areacode = $exploded[1];
    $number = $exploded[2];
    $ext = (!empty($exploded[3])?$exploded[3]:'');

    if($countrycode=='+1'){
        $strphone = strlen($number);
        if ($strphone == 7) { // auto-format US PHones

            $prefix = substr($number,0,3);
            $suffix = substr($number,-4);

        }
        $phone = $countrycode.' '.$areacode.' '.$prefix.'-'.$suffix.' '.$ext;

    }

    return $phone;
}



echo format_phonenumbers('+1 (714) 1234567'); // US domestic
echo '<br>';
echo format_phonenumbers('+966 (1) 1234567 x555'); // international

?>

这形成了我需要的格式,但我很好奇是否有人认为我可以更好地做到这一点。就像使用正则表达式检查器一样,它在括号之后但在扩展之前找到任何内容,而不是使用explode()函数。

1 个答案:

答案 0 :(得分:0)

类似的东西:

function format_phonenumbers($phone)
{
    return preg_replace_callback(
        '/([)]\s*)(\d{3,3}(\d+)/',
        function ($match) {
            return $match[1] . $match[2] . '-' . $match[3];
        },
        $phone
    );
}

这应该可行,但需要PHP 5.3.0或更高版本(如果不是,则必须使用create_function)。如果它有任何更好的话,它是有争议的。