我使用以下正则表达式来确保输入的是有效的电话号码。目前,如果输入的数字超过10位,则不会标记错误。
如何解决这个问题?
public function phoneNumber($value) {
if (preg_match("/^'(?[0-9]{3}')? *-? *[0-9]{3} *-? *[0-9]{4}$/", $value)) {
return true;
}
return false;
}
下面是一个测试用例,当前显示为一个有效的电话号码,当它不应该:
35353535355535555555
如果您只对数字感兴趣,您可以过滤掉其他内容并检查结果:
public function phoneNumber($value) {
$filtered = preg_replace("/'D/","",$value);
return strlen($filtered) == 10;
}
过滤掉外部号码或带有扩展名的号码不是一个好主意。下面是一个示例,我使用它将普通数字转换为CRM注入的特定格式。包括垃圾邮件评分。
<?php
function phoneNumber($value) {
$phoneScore = 0;
$numbers = preg_replace('![^0-9]!','',$value);
//if it's too small to be a US number, then ramp it up.
if (!empty($value)&&(strlen($numbers) < 10)){
$phoneScore = $phoneScore + 3;
} elseif (empty($value)){
$phoneScore = $phoneScore + 10;
}
return $phoneScore;
}
$numbers = array(
'(911 -535 -3535',
'800.555.1212',
'800 458 2180',
'800 - 458 2180',
'800 - 458-2180',
'',
'800-555-1212 ext# 212',
'+49 (0)69 974640',
'+86 (021) 5466-2808',
'+66 (02) 261-3525',
'+44 (020) 7626-0224',
'123456',
);
$patterns = array('![^0-9xX#+]!','!-+!','!-?[xX#]-?!','!#+!','!#!','!^-!');
$replacements = array("-","-",'#','#',' #','');
foreach ($numbers as $value){
$score = phoneNumber($value);
$clean_num = preg_replace($patterns,$replacements,$value);
echo "$value = Score $score.<br />'n Cleaned Number = $clean_num<br />'n<br />'n";
}
?>
输出如下:
(911 -535 -3535 =得分0。清洗号码= 911-535-3535
800.555.1212 =得分0。清洗号码= 800-555-1212
800 458 2180 =得分0。清洗号码= 800-458-2180
800 - 458 2180 =得分0。清洗号码= 800-458-2180
800 - 458-2180 =得分0。清洗号码= 800-458-2180
=得分10分。清洗次数=
800-555-1212 ext# 212 =得分0。清洗号码= 800-555-1212 #212
+49(0)69 974640 =得分0。清洗编号= +49-0-69-974640
+86(021) 5466-2808 =得分0。清洗号码= +86-021-5466-2808
+66(02) 261-3525 =得分0。清洗号码= +66-02-261-3525
+44(020) 7626-0224 =得分0。清洗号码= +44-020-7626-0224
123456 =得分3。清洗号码= 123456