鉴于没有其他人提到这一点,我会从数字中删除所有非数字字符。完成后,您可以使用正则表达式轻松获取数字,这样任何格式都是有效的,几乎无论用户输入什么,您都可以按照自己的意愿进行格式化:
$phone = preg_replace("~[^0-9]~", "", $phone);
preg_match('~([0-9]{3})([0-9]{3})([0-9]{4})~', $phone, $matches);
if (!empty($matches)) {
$display = "<span id='telephone'><span class='spacer'>(" .
$matches[1] . ")</span>" . $matches[2] . "-" . $matches[3] . "</span>";
}else {
$display = "An invalid phone number was entered.";
}
只要有 10 位数字,无论如何输入电话号码都应该这样做。
更新
您还可以将preg_replace 技术与substr 一起使用,而无需使用preg_match。这实际上是我的首选解决方案。
$phone = preg_replace("~[^0-9]~", "", $phone);
if (strlen($phone) == 10) {
$display = "<span id='telephone'><span class='spacer'>(" .
substr($phone,0,3) . ")</span>" . substr($phone,2,3) . "-" . substr($phone,5,4) . "</span>";
}else {
$display = "An invalid phone number was entered.";
}