我只將電話號碼存儲爲數字。這個數據庫中的軍刀空間。格式可以改變。另外,編寫簡潔的代碼時,需要重新使用代碼來爭取。 此功能可以減少數據庫表格中少於100個左右格式化電話號碼的空間。
function format_phone($phone = '', $convert = false, $trim = true){
// If we have not entered a phone number just return empty
if (empty($phone)) {
return '';
}
// Strip out any extra characters that we do not need only keep letters and numbers
$phone = preg_replace("/[^0-9A-Za-z]/", "", $phone);
// Do we want to convert phone numbers with letters to their number equivalent?
// Samples are: 1-800-TERMINIX, 1-800-FLOWERS, 1-800-Petmeds
if ($convert == true) {
$replace = array('2'=>array('a','b','c'),
'3'=>array('d','e','f'),
'4'=>array('g','h','i'),
'5'=>array('j','k','l'),
'6'=>array('m','n','o'),
'7'=>array('p','q','r','s'),
'8'=>array('t','u','v'),
'9'=>array('w','x','y','z'));
// Replace each letter with a number
// Notice this is case insensitive with the str_ireplace instead of str_replace
foreach($replace as $digit=>$letters) {
$phone = str_ireplace($letters, $digit, $phone);
}
}
// If we have a number longer than 11 digits cut the string down to only 11
// This is also only ran if we want to limit only to 11 characters
if ($trim == true && strlen($phone)>11) {
$phone = substr($phone, 0, 11);
}
// Perform phone number formatting here
if (strlen($phone) == 7) {
return preg_replace("/([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "$1-$2", $phone);
} elseif (strlen($phone) == 10) {
return preg_replace("/([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "($1) $2-$3", $phone);
} elseif (strlen($phone) == 11) {
return preg_replace("/([0-9a-zA-Z]{1})([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "$1($2) $3-$4", $phone);
}
// Return original phone if not 7, 10 or 11 digits long
return $phone;
}
這取決於,如果您的應用程序將在全球範圍內使用,那麼您必須在需要時保留原始值和格式,並且顯然有一點性能下降。否則,你可能會保持一種格式。 – mohkhan
在像巴西這樣的國家,我們有代碼55 –
我一直認爲你應該在演示中做 –