格式化数据库中的电话号码

时间:2017-06-26 15:27:48

标签: php mysql

我还是PHP的新手,并且在弄清楚如何格式化从数据库中提取的电话号码时遇到了一些麻烦。

我正在使用以下代码生成一个表:

<?php
include ('database.php');
$result = mysql_query("SELECT * FROM members") or die(mysql_error());

echo "<div class='container'>";
include ("header.php");
echo "<h4>Members</h4><div class='pull-right'><a class='btn btn-primary btn-sm' href='new.php'>New Member</a></div>";
echo "<hr>";
echo "<table class='table table-striped'>";
echo "<tr><th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Birthday</th><th>Phone Number</th><th></th> <th></th></tr>";
while ($row = mysql_fetch_array($result)) {
    echo "<tr>";
    echo '<td>' . $row['id'] . '</td>';
    echo '<td>' . $row['first_name'] . '</td>';
    echo '<td>' . $row['last_name'] . '</td>';
    echo '<td>' . $row['birthday'] . '</td>';
    echo '<td>' . $row['phone_number'] . '</td>';
    echo '<td><a href="edit.php?id=' . $row['id'] . '"><span class="fui-new"></span></a></td>';
    echo '<td><a href="delete.php?id=' . $row['id'] . '"><span class="fui-trash"></span></a></td>';
    echo "</tr>";
}
echo "</table>";
echo "</div>";
?>

我想以常规的美国时尚格式化它们:(xxx)xxx - xxx。

我提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这是我编写的用于格式化10位数电话号码的功能,如美国,加拿大和其他一些国家/地区使用。

function FormatPhoneNum($ph) {
$ph = str_replace(array('(',')','-','.', ' '), '', $ph);
if (strlen($ph) ==10){ $ph = '('. $ph['0']. $ph['1']. $ph['2'].')     '.$ph['3'].$ph['4'].$ph['5'].'-'.$ph['6'].$ph['7'].$ph['8'].$ph['9'];}
return $ph;
} 

在脚本的某处添加该功能,然后使用像这样的功能......

 echo '<td>' . FormatPhoneNum($row['phone_number']) . '</td>';