格式并在PHP报告页面上显示电话号码

问题描述:

我有一个名为customer_phone的数据库字段,它在输入时存储。它是这样显示的报告页面上立即从数据库中:格式并在PHP报告页面上显示电话号码

print "Phone: $customer_phone<br>"; 

我想从数据库字段中的数据,如果剔除任何额外字符的任意只是数字(例如:xxx-xxx-xxxxxxxxxxxxxx ),然后以这种格式显示在页面上:

(xxx) xxx-xxxx 

我发现功能的脚本来做到这一点,但一直没能得到他们的工作。

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

我是一个PHP newby,并希望得到任何帮助。

$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 
+0

谢谢,这真是棒极了。 – user1334831 2012-04-15 21:37:32

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); ?> 
+0

完美运作。非常感谢! – user1334831 2012-04-15 21:37:06

+0

没问题,如果你是如此善良,以决定一个胜利者,并接受答案,我们将不胜感激:) – Dale 2012-04-15 21:38:32