您好,正在从事一些维护项目。但是在该代码上,有人添加了preg_match表达式以禁止免费电话号码。免费电话号码以区号800、888、877、866、855或844开头。它们的格式为800-xxx-xxxx或1- 800-xxx-xxxx或(800)xxx-xxxx或800xxxxxxx或1800xxxxxxx。等
如果该号码是免费电话号码,则引发错误“请在此处输入本地电话号码,而不是免费电话号码。” 下面是我的代码:-
$getphone = $_POST['phone'];
/* ISSUE: This catches
1-800-450-7006
1 (800) 450-7006
1(800) 450-7006
but is not catching
(800) 450-7006
*/
if(!preg_match('/^(?!(?:1-)?(\\$|#|8(00|55|66|77|88)))\(?[\\s.-]*([0-9]{3})?[\\s.-]*\)?[\\s.-]*[0-9]{3}[\\s.-]*[0-9]{4}$/', $getphone)){
// Need to redirect back, not to profile
echo 'Please enter a local phone number here, not a toll free number'; die;
}
任何人都可以帮助我如何检查这种情况(800)450-7006。谢谢
答案 0 :(得分:1)
我建议在括号的开头(或不包括)“排除”特定数字:
'~^(?!(?:1-)?(?:\$|#|(?:\((8(?:00|55|66|77|88))\)|(?1))))\(?[\s.-]*([0-9]{3})?[\s.-]*\)?[\s.-]*[0-9]{3}[\s.-]*[0-9]{4}$~'
请参见regex demo
我将8(00|55|66|77|88)
替换为(?:\((8(?:00|55|66|77|88))\)|(?1))
,这是一个不受捕获的组,它与以下两种选择均匹配:
\((8(?:00|55|66|77|88))\)
-(
,800
,855
,866
,877
,888
,然后是{{1} } )
-或|
-整个(?1)
,第1组,模式。答案 1 :(得分:0)
<?php
/* 800, 888, 877, 866, 855 or 844. They will be formatted as
800-xxx-xxxx or 1-800-xxx-xxxx or (800) xxx-xxxx or
800xxxxxxx or 1800xxxxxxx */
$phone = $_POST['phone'];
// remove everything that is not a number
$phone = preg_replace('/[^\d]/', '', $phone);
// look for your pattern in the "cleaned" string
if(!preg_match('/^1?8(88|77|66|55|44|00)/', $phone)){
echo 'error';
}
?>