我在一个短信应用程序上工作,需要能够将发送者的电话号码从+11234567890转换到1234567890,以便它可以与MySQL数据库中的记录进行比较。
数字以后一种格式存储,以便在网站上的其他地方使用,我不愿更改这种格式,因为这将需要修改大量代码。
我该如何使用?
谢谢!
发布于 2011-01-17 05:52:27
$data = '+11234567890';
if( preg_match( '/^\+\d(\d{3})(\d{3})(\d{4})$/', $data, $matches ) )
{
$result = $matches[1] . '-' .$matches[2] . '-' . $matches[3];
return $result;
}
发布于 2012-05-25 00:22:18
这是一个美国电话格式化程序,可以处理比任何当前答案更多版本的数字。
$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";
}
下面是正则表达式的细目:
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 ")"
更新: 2015年3月11日,使用{0,7}
代替{,7}
发布于 2013-01-05 08:33:02
此功能将设置国际(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;
}
https://stackoverflow.com/questions/4708248
复制相似问题