【问题标题】:format and display a phone number on a report page in PHP在 PHP 的报告页面上格式化并显示电话号码
【发布时间】:2012-04-15 17:41:32
【问题描述】:

我有一个名为customer_phone 的数据库字段,它在输入时存储。它现在从数据库中显示在报告页面上,如下所示:

print  "Phone: $customer_phone<br>";

我想从数据库字段中获取数据,去掉任何多余的字符(如果有的话)只剩下数字(例如:xxx-xxx-xxxxxxxxxxxxxx),然后以这种格式显示在页面上:

(xxx) xxx-xxxx

我找到了执行此操作的函数脚本,但无法让它们工作。

我需要从数据库字段中获取数据,重新格式化并显示在页面上。

我是 PHP 新手,希望能提供任何帮助。

【问题讨论】:

    标签: php phone-number


    【解决方案1】:
    function format_telephone($phone_number)
    {
        $cleaned = preg_replace('/[^[:digit:]]/', '', $phone_number);
        preg_match('/(\d{3})(\d{3})(\d{4})/', $cleaned, $matches);
        return "({$matches[1]}) {$matches[2]}-{$matches[3]}";
    }
    

    有一个功能可以按照你的要求做,就这样称呼它

    <?php echo format_telephone($customer_phone); ?>
    

    【讨论】:

    • 没问题,如果您能决定获胜者并接受答案,我们将不胜感激:)
    【解决方案2】:
    $phone_number= preg_replace('/[^0-9]+/', '', $phone_number); //Strip all non number characters
    echo preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone_number) //Re Format it
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-05
      • 2018-08-14
      • 1970-01-01
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多