2

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

print  "Phone: $customer_phone<br>";

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

(xxx) xxx-xxxx

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

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

我是 PHP 新手,如果有任何帮助,我将不胜感激。

4

2 回答 2

14
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); ?>
于 2012-04-15T17:54:36.383 回答
4
$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
于 2012-04-15T17:49:29.507 回答