在PHP中格式化电话号码

我正在使用短信应用程序 ,需要能够将发件人的电话号码从+11234567890转换123-456-7890,以便将其与MySQL数据库中的logging进行比较。

数字以后者的格式存储在网站的其他地方,我宁愿不改变这种格式,因为它需要修改很多代码。

我怎样才能用PHP来解决这个问题?

谢谢!

$data = '+11234567890'; if( preg_match( '/^\+\d(\d{3})(\d{3})(\d{4})$/', $data, $matches ) ) { $result = $matches[1] . '-' .$matches[2] . '-' . $matches[3]; return $result; } 

这是一个美国的手机格式化工具,比任何当前的答案更多的数字版本。

 $numbers = explode("\n", '(111) 222-3333 ((111) 222-3333 1112223333 111 222-3333 111-222-3333 (111)2223333 +11234567890 1-8002353551 123-456-7890 -Hello! +1 - 1234567890 '); foreach($numbers as $number) { print preg_replace('~.*(\d{3})[^\d]{0,7}(\d{3})[^\d]{0,7}(\d{4}).*~', '($1) $2-$3', $number). "\n"; } 

这里是正则expression式的细分:

 Cell: +1 999-(555 0001) .* zero or more of anything "Cell: +1 " (\d{3}) three digits "999" [^\d]{0,7} zero or up to 7 of something not a digit "-(" (\d{3}) three digits "555" [^\d]{0,7} zero or up to 7 of something not a digit " " (\d{4}) four digits "0001" .* zero or more of anything ")" 

更新date:2015年3月11日,使用{0,7}而不是{,7}

此function将格式化国际(10+数字),非国际(10位数字)或老学校(7位数字)的电话号码。 除10+,10或7位以外的任何数字将保持未格式化。

 function formatPhoneNumber($phoneNumber) { $phoneNumber = preg_replace('/[^0-9]/','',$phoneNumber); if(strlen($phoneNumber) > 10) { $countryCode = substr($phoneNumber, 0, strlen($phoneNumber)-10); $areaCode = substr($phoneNumber, -10, 3); $nextThree = substr($phoneNumber, -7, 3); $lastFour = substr($phoneNumber, -4, 4); $phoneNumber = '+'.$countryCode.' ('.$areaCode.') '.$nextThree.'-'.$lastFour; } else if(strlen($phoneNumber) == 10) { $areaCode = substr($phoneNumber, 0, 3); $nextThree = substr($phoneNumber, 3, 3); $lastFour = substr($phoneNumber, 6, 4); $phoneNumber = '('.$areaCode.') '.$nextThree.'-'.$lastFour; } else if(strlen($phoneNumber) == 7) { $nextThree = substr($phoneNumber, 0, 3); $lastFour = substr($phoneNumber, 3, 4); $phoneNumber = $nextThree.'-'.$lastFour; } return $phoneNumber; } 

假设你的电话号码总是有这个确切的格式,你可以使用这个片段:

 $from = "+11234567890"; $to = sprintf("%s-%s-%s", substr($from, 2, 3), substr($from, 5, 3), substr($from, 8)); 

电话号码很难。 对于更强大的国际化解决scheme,我会推荐这个维护良好的PHP端口的Google libphonenumber库。

像这样使用它,

 use libphonenumber\NumberParseException; use libphonenumber\PhoneNumber; use libphonenumber\PhoneNumberFormat; use libphonenumber\PhoneNumberUtil; $phoneUtil = PhoneNumberUtil::getInstance(); $numberString = "+12123456789"; try { $numberPrototype = $phoneUtil->parse($numberString, "US"); echo "Input: " . $numberString . "\n"; echo "isValid: " . ($phoneUtil->isValidNumber($numberPrototype) ? "true" : "false") . "\n"; echo "E164: " . $phoneUtil->format($numberPrototype, PhoneNumberFormat::E164) . "\n"; echo "National: " . $phoneUtil->format($numberPrototype, PhoneNumberFormat::NATIONAL) . "\n"; echo "International: " . $phoneUtil->format($numberPrototype, PhoneNumberFormat::INTERNATIONAL) . "\n"; } catch (NumberParseException $e) { // handle any errors } 

你会得到以下输出:

 Input: +12123456789 isValid: true E164: +12123456789 National: (212) 345-6789 International: +1 212-345-6789 

我build议使用E164格式进行重复检查。 你也可以检查号码是否是一个实际的手机号码(使用PhoneNumberUtil::getNumberType() ),或者它是否是美国号码(使用PhoneNumberUtil::getRegionCodeForNumber() )。

作为奖励,图书馆可以处理几乎任何input。 例如,如果你select通过上面的代码运行1-800-JETBLUE ,你会得到

 Input: 1-800-JETBLUE isValid: true E164: +18005382583 National: (800) 538-2583 International: +1 800-538-2583 

NEATO。

对美国以外的国家来说,它的作用也很好。 只需在parse()参数中使用另一个ISO国家/地区代码即可。

这是我的美国唯一的解决scheme,区号是一个可选组件,扩展需要分隔符,和正则expression式:

 function formatPhoneNumber($s) { $rx = "/ (1)?\D* # optional country code (\d{3})?\D* # optional area code (\d{3})\D* # first three (\d{4}) # last four (?:\D+|$) # extension delimiter or EOL (\d*) # optional extension /x"; preg_match($rx, $s, $matches); if(!isset($matches[0])) return false; $country = $matches[1]; $area = $matches[2]; $three = $matches[3]; $four = $matches[4]; $ext = $matches[5]; $out = "$three-$four"; if(!empty($area)) $out = "$area-$out"; if(!empty($country)) $out = "+$country-$out"; if(!empty($ext)) $out .= "x$ext"; // check that no digits were truncated // if (preg_replace('/\D/', '', $s) != preg_replace('/\D/', '', $out)) return false; return $out; } 

这里是testing它的脚本:

 $numbers = [ '3334444', '2223334444', '12223334444', '12223334444x5555', '333-4444', '(222)333-4444', '+1 222-333-4444', '1-222-333-4444ext555', 'cell: (222) 333-4444', '(222) 333-4444 (cell)', ]; foreach($numbers as $number) { print(formatPhoneNumber($number)."<br>\r\n"); } 

我看到这是可能的使用一些正则expression式,或一些substr调用(假设input总是这种格式,并不会改变长度等)

就像是

 $in = "+11234567890"; $output = substr($in,2,3)."-".substr($in,6,3)."-".substr($in,10,4); 

应该这样做。

这里有一个简单的function,用更欧洲(或瑞典)的方式来格式化7至10位数字的电话号码:

 function formatPhone($num) { $num = preg_replace('/[^0-9]/', '', $num); $len = strlen($num); if($len == 7) $num = preg_replace('/([0-9]{2})([0-9]{2})([0-9]{3})/', '$1 $2 $3', $num); elseif($len == 8) $num = preg_replace('/([0-9]{3})([0-9]{2})([0-9]{3})/', '$1 - $2 $3', $num); elseif($len == 9) $num = preg_replace('/([0-9]{3})([0-9]{2})([0-9]{2})([0-9]{2})/', '$1 - $2 $3 $4', $num); elseif($len == 10) $num = preg_replace('/([0-9]{3})([0-9]{2})([0-9]{2})([0-9]{3})/', '$1 - $2 $3 $4', $num); return $num; } 

尝试像这样:

 preg_replace('/\d{3}/', '$0-', str_replace('.', null, trim($number)), 2); 

这需要$ 8881112222 $ 888-111-2222 。 希望这可以帮助。

另一种select – 轻松更新,从configuration接收格式。

 $numbers = explode("\n", '(111) 222-3333 ((111) 222-3333 1112223333 111 222-3333 111-222-3333 (111)2223333 +11234567890 1-8002353551 123-456-7890 -Hello! +1 - 1234567890 '); foreach( $numbers AS $number ){ echo comMember_format::phoneNumber($number) . '<br>'; } // ************************************************************************ // Format Phone Number public function phoneNumber( $number ){ $txt = preg_replace('/[\s\-|\.|\(|\)]/','',$number); $format = '[$1?$1 :][$2?($2):x][$3: ]$4[$5: ]$6[$7? $7:]'; if( preg_match('/^(.*)(\d{3})([^\d]*)(\d{3})([^\d]*)(\d{4})([^\d]{0,1}.*)$/', $txt, $matches) ){ $result = $format; foreach( $matches AS $k => $v ){ $str = preg_match('/\[\$'.$k.'\?(.*?)\:(.*?)\]|\[\$'.$k.'\:(.*?)\]|(\$'.$k.'){1}/', $format, $filterMatch); if( $filterMatch ){ $result = str_replace( $filterMatch[0], (!isset($filterMatch[3]) ? (strlen($v) ? str_replace( '$'.$k, $v, $filterMatch[1] ) : $filterMatch[2]) : (strlen($v) ? $v : (isset($filterMatch[4]) ? '' : (isset($filterMatch[3]) ? $filterMatch[3] : '')))), $result ); } } return $result; } return $number; } 

这需要7,10和11位,删除额外的字符,并通过从右到左的string添加破折号。 将短划线改为空格或点。

 $raw_phone = preg_replace('/\D/', '', $raw_phone); $temp = str_split($raw_phone); $phone_number = ""; for ($x=count($temp)-1;$x>=0;$x--) { if ($x === count($temp) - 5 || $x === count($temp) - 8 || $x === count($temp) - 11) { $phone_number = "-" . $phone_number; } $phone_number = $temp[$x] . $phone_number; } echo $phone_number; 

所有,

我想我修好了。 为当前的input文件工作,并有以下2个function来完成这个工作!

函数format_phone_number:

  function format_phone_number ( $mynum, $mask ) { /*********************************************************************/ /* Purpose: Return either masked phone number or false */ /* Masks: Val=1 or xxx xxx xxxx */ /* Val=2 or xxx xxx.xxxx */ /* Val=3 or xxx.xxx.xxxx */ /* Val=4 or (xxx) xxx xxxx */ /* Val=5 or (xxx) xxx.xxxx */ /* Val=6 or (xxx).xxx.xxxx */ /* Val=7 or (xxx) xxx-xxxx */ /* Val=8 or (xxx)-xxx-xxxx */ /*********************************************************************/ $val_num = self::validate_phone_number ( $mynum ); if ( !$val_num && !is_string ( $mynum ) ) { echo "Number $mynum is not a valid phone number! \n"; return false; } // end if !$val_num if ( ( $mask == 1 ) || ( $mask == 'xxx xxx xxxx' ) ) { $phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~', '$1 $2 $3'." \n", $mynum); return $phone; } // end if $mask == 1 if ( ( $mask == 2 ) || ( $mask == 'xxx xxx.xxxx' ) ) { $phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~', '$1 $2.$3'." \n", $mynum); return $phone; } // end if $mask == 2 if ( ( $mask == 3 ) || ( $mask == 'xxx.xxx.xxxx' ) ) { $phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~', '$1.$2.$3'." \n", $mynum); return $phone; } // end if $mask == 3 if ( ( $mask == 4 ) || ( $mask == '(xxx) xxx xxxx' ) ) { $phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~', '($1) $2 $3'." \n", $mynum); return $phone; } // end if $mask == 4 if ( ( $mask == 5 ) || ( $mask == '(xxx) xxx.xxxx' ) ) { $phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~', '($1) $2.$3'." \n", $mynum); return $phone; } // end if $mask == 5 if ( ( $mask == 6 ) || ( $mask == '(xxx).xxx.xxxx' ) ) { $phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~', '($1).$2.$3'." \n", $mynum); return $phone; } // end if $mask == 6 if ( ( $mask == 7 ) || ( $mask == '(xxx) xxx-xxxx' ) ) { $phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~', '($1) $2-$3'." \n", $mynum); return $phone; } // end if $mask == 7 if ( ( $mask == 8 ) || ( $mask == '(xxx)-xxx-xxxx' ) ) { $phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~', '($1)-$2-$3'." \n", $mynum); return $phone; } // end if $mask == 8 return false; // Returns false if no conditions meet or input } // end function format_phone_number 

函数validate_phone_number:

  function validate_phone_number ( $phone ) { /*********************************************************************/ /* Purpose: To determine if the passed string is a valid phone */ /* number following one of the establish formatting */ /* styles for phone numbers. This function also breaks */ /* a valid number into it's respective components of: */ /* 3-digit area code, */ /* 3-digit exchange code, */ /* 4-digit subscriber number */ /* and validates the number against 10 digit US NANPA */ /* guidelines. */ /*********************************************************************/ $format_pattern = '/^(?:(?:\((?=\d{3}\)))?(\d{3})(?:(?<=\(\d{3})\))'. '?[\s.\/-]?)?(\d{3})[\s\.\/-]?(\d{4})\s?(?:(?:(?:'. '(?:e|x|ex|ext)\.?\:?|extension\:?)\s?)(?=\d+)'. '(\d+))?$/'; $nanpa_pattern = '/^(?:1)?(?(?!(37|96))[2-9][0-8][0-9](?<!(11)))?'. '[2-9][0-9]{2}(?<!(11))[0-9]{4}(?<!(555(01([0-9]'. '[0-9])|1212)))$/'; // Init array of variables to false $valid = array('format' => false, 'nanpa' => false, 'ext' => false, 'all' => false); //Check data against the format analyzer if ( preg_match ( $format_pattern, $phone, $matchset ) ) { $valid['format'] = true; } //If formatted properly, continue //if($valid['format']) { if ( !$valid['format'] ) { return false; } else { //Set array of new components $components = array ( 'ac' => $matchset[1], //area code 'xc' => $matchset[2], //exchange code 'sn' => $matchset[3] //subscriber number ); // $components = array ( 'ac' => $matchset[1], //area code // 'xc' => $matchset[2], //exchange code // 'sn' => $matchset[3], //subscriber number // 'xn' => $matchset[4] //extension number // ); //Set array of number variants $numbers = array ( 'original' => $matchset[0], 'stripped' => substr(preg_replace('[\D]', '', $matchset[0]), 0, 10) ); //Now let's check the first ten digits against NANPA standards if(preg_match($nanpa_pattern, $numbers['stripped'])) { $valid['nanpa'] = true; } //If the NANPA guidelines have been met, continue if ( $valid['nanpa'] ) { if ( !empty ( $components['xn'] ) ) { if ( preg_match ( '/^[\d]{1,6}$/', $components['xn'] ) ) { $valid['ext'] = true; } // end if if preg_match } else { $valid['ext'] = true; } // end if if !empty } // end if $valid nanpa //If the extension number is valid or non-existent, continue if ( $valid['ext'] ) { $valid['all'] = true; } // end if $valid ext } // end if $valid return $valid['all']; } // end functon validate_phone_number 

注意我在类lib中有这个,因此第一个函数/方法的“self :: validate_phone_number”调用。

注意“validate_phone_number”函数的第32行,我添加了:

  if ( !$valid['format'] ) { return false; } else { 

如果没有有效的电话号码,我可以得到所需的虚假回报。

仍然需要对更多的数据进行testing,但是使用当前的格式处理当前的数据,并且对这个特定的数据批次使用样式“8”。

我还注意到了“扩展”的逻辑,因为我经常从中得到错误,看到我的数据中没有任何信息。

这是没有国家代码的英国固定电话

 function format_phone_number($number) { $result = preg_replace('~.*(\d{2})[^\d]{0,7}(\d{4})[^\d]{0,7}(\d{4}).*~', '$1 $2 $3', $number); return $result; } 

结果:

 2012345678 becomes 20 1234 5678 

它比Reg-Ex快。

$ input =“0987654321”;

echo $ output = substr($ input,-10,-7)。“ – ”。substr($ input,-7,-4)。“ – ”。substr($ input,-4);

我知道OP正在请求123-456-7890格式,但根据John Dul的回答 ,我修改了它以返回括号格式的电话号码,例如(123)456-7890。 这个只能处理7位和10位数字。

 function format_phone_string( $raw_number ) { // remove everything but numbers $raw_number = preg_replace( '/\D/', '', $raw_number ); // split each number into an array $arr_number = str_split($raw_number); // add a dummy value to the beginning of the array array_unshift( $arr_number, 'dummy' ); // remove the dummy value so now the array keys start at 1 unset($arr_number[0]); // get the number of numbers in the number $num_number = count($arr_number); // loop through each number backward starting at the end for ( $x = $num_number; $x >= 0; $x-- ) { if ( $x === $num_number - 4 ) { // before the fourth to last number $phone_number = "-" . $phone_number; } else if ( $x === $num_number - 7 && $num_number > 7 ) { // before the seventh to last number // and only if the number is more than 7 digits $phone_number = ") " . $phone_number; } else if ( $x === $num_number - 10 ) { // before the tenth to last number $phone_number = "(" . $phone_number; } // concatenate each number (possibly with modifications) back on $phone_number = $arr_number[$x] . $phone_number; } return $phone_number; }