【问题标题】:preg_match phone numbers with removalpreg_match 删除的电话号码
【发布时间】:2013-12-29 18:25:16
【问题描述】:

我正在尝试检查字符串是否包含电话号码。有几种电话号码格式。请参阅下面的列表。我试图将它们添加到 preg_match 检查,之后它们可以从字符串中删除。

06-12341234 - [0-9]{2}[\-][0-9]{8}
0612341234 - [0-9]{10}
+31 6 12341234 
31612341234
0031 6 12341234 - [0-9]{4}[\s][0-9]{1}[\s][0-9]{8}
+31612341234
0031612341234 - [0-9]{11}
06 1234 1234 - [0-9]{2}[\s][0-9]{4}[\s][0-9]{4}
06-1234 1234 - [0-9]{2}[\-][0-9]{4}[\s][0-9]{4}

还有更多。但是没有更好的检查来查找电话号码并替换它们吗?下面的 sn-p 不会从字符串中删除电话号码。

if(preg_match('/
        [0-9]{2}[\-][0-9]{8}| 
        [0-9]{4}[\s][0-9]{1}[\s][0-9]{8}|
        [0-9]{10}|
        [0-9]{11}|
        /', $Message)){
    //URLS
    $pattern = "/
        [0-9]{2}[\-][0-9]{8}| 
        [0-9]{4}[\s][0-9]{1}[\s][0-9]{8}|
        [0-9]{10}|
        [0-9]{11}|
        /";
    $replacement = "[removed]";
    $Message = preg_replace($pattern, $replacement, $string);
    $Score = $Score+20;
}

【问题讨论】:

    标签: php validation preg-match


    【解决方案1】:

    我认为使用 preg_replace() 是正确的方法,但您不必先检查 preg_match()。您可以在之后检查字符串是否相同。如果不一样,你会做你需要的其他事情,比如增加分数。

    所以你的代码应该是这样的:

    $replacement = "[removed]";
    $message = preg_replace('/(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?/', $replacement, $string);
    if ($message != $replacement) {
        $score = $score + 20;
    }
    

    注意:我在上面找到了匹配电话号码的模式,我不确定它是否适用于您的数据,您应该自己测试一下。

    【讨论】:

      【解决方案2】:

      尝试将字母 x 添加到模式的末尾:

      而不是这个:

      $pattern = '/
              [0-9]{2}[\-][0-9]{8}| 
              [0-9]{4}[\s][0-9]{1}[\s][0-9]{8}|
              [0-9]{10}|
              [0-9]{11}|
              /';
      

      使用这个:

      $pattern = '/
              [0-9]{2}[\-][0-9]{8}| 
              [0-9]{4}[\s][0-9]{1}[\s][0-9]{8}|
              [0-9]{10}|
              [0-9]{11}|
              /x';
      

      更好的是,定义一次模式并重用它:

      // If the pattern is the same, there's no point in writing it twice.
      // Save some time and possibly prevent errors by using the same pattern
      // in each check.
      $pattern = '/
              [0-9]{2}[\-][0-9]{8}| 
              [0-9]{4}[\s][0-9]{1}[\s][0-9]{8}|
              [0-9]{10}|
              [0-9]{11}|
              /x';
      if (preg_match($pattern, $Message)) {
          //URLS
          $replacement = "[removed]";
          $Message = preg_replace($pattern, $replacement, $string);
          $Score = $Score+20;
      }
      

      【讨论】:

      • 嗨,刚刚测试了您的更改。但是,它会删除整个字符串,而不是其中的一部分。我应该更改什么以仅删除电话号码?
      • 好吧,我没有看到 $string 在任何地方定义,所以我不确定它来自哪里...您是否试图从 preg_match() 中生成一组匹配项?或者您要更换哪个部分?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多