【问题标题】:PHP regex vs explode() for phone numberPHP正则表达式与explode()的电话号码
【发布时间】:2011-10-25 18:02:11
【问题描述】:

我一直在搞乱一些正则表达式,但我遇到了一个小问题,我的电话号码格式更复杂。

这是我正在使用的:

$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() 函数。

【问题讨论】:

  • ... output from a mysql query... .MySQL 中的数字是如何存储的?如果你有 mysql 格式化多个字段的数字,那么只需输出这些单独的字段,这样你就不必撤销你刚刚在 MySQL 中所做的事情。
  • 那么等等,您想获取数据库中已有的字符串,并将其形式更改为更易读的形式吗? (只是为了让我完全理解你的问题)

标签: php explode


【解决方案1】:

类似:

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)。然而,如果它更好,它是有争议的。

【讨论】:

    猜你喜欢
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 2014-02-15
    • 1970-01-01
    相关资源
    最近更新 更多