不允许在 php preg_match 正则表达式中使用免费电话号码

Don't allow toll free numbers in php preg_match regexp

您好,我正在进行一些维护项目。但是有人在该代码上添加了 preg_match 表达式,表示不允许使用免费电话号码。免费电话号码以区号 800、888、877、866、855 或 844 开头。它们将被格式化为 800-xxx- xxxx 或 1-800-xxx-xxxx 或 (800) xxx-xxxx 或 800xxxxxxx 或 1800xxxxxxx。等等

如果号码是免费电话,抛出错误"Please enter a local phone number here, not a toll free number." 下面是我的代码:-

$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。谢谢

<?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';
 }

?>

我建议 "excluding" 开始时在括号内(或不在括号内)的具体数字:

'~^(?!(?: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))\)|(?1)) 替换了 8(00|55|66|77|88),一个非捕获组匹配两个备选方案:

  • \((8(?:00|55|66|77|88))\) - (800855866877888 然后 )
  • | - 或
  • (?1) - 整个 8(?:00|55|66|77|88),第 1 组,模式。