【问题标题】:Regexp: how to remove everything except another regexp?正则表达式:如何删除除另一个正则表达式之外的所有内容?
【发布时间】:2010-10-16 23:18:22
【问题描述】:

我有一些正则表达式(如 ^\w+[\w-.]\@\w+((-\w+)|(\w)).[az]{2,3} $, 以匹配正确的电子邮件),但我不知道如何删除与字符串中的正则表达式不匹配的所有内容。

保留电子邮件示例,我需要一种方法来解决问题,例如

$myString = "This is some text, the email is here example@example.com, and other things over here";

如果字符串中没有电子邮件,我只需要返回“example@example.com”或布尔值 false。

当然,电子邮件只是一个示例,有时我需要删除除整数/浮点数等之外的所有内容...

我用谷歌搜索了很多,但没有找到任何东西。

【问题讨论】:

    标签: php regex


    【解决方案1】:

    如果您将正则表达式括在括号中并使用preg_matchpreg_match_all,它将仅返回与正则表达式匹配的字符串部分:

    $myString = "This is some text, the email is here example@example.com, and other things over here";
    preg_match("/(\w+[\w-.]\@\w+((-\w+)|(\w)).[a-z]{2,3})/", $myString, $matches);
    print_r($matches);
    

    注意,我还去掉了字符串分隔符的开头和结尾,因为在这种情况下不需要它们。

    【讨论】:

      【解决方案2】:

      使用preg_match_all function 匹配所有匹配项。 preg_match_all 函数本身返回匹配数,如果发生错误,则返回 false

      所以:

      $myString = "This is some text, the email is here example@example.com, and other things over here";
      if (($num = preg_match_all('/\w+[\w-.]\@\w+((-\w+)|(\w)).[a-z]{2,3}/', $myString, $matches)) !== false) {
          echo $num.' matches have been found.';
          var_dump($matches);
      } else {
          // error
      }
      

      【讨论】:

        【解决方案3】:

        您的正则表达式需要删除 $ 和 ^ 才能工作,这些符号无法在字符串中间找到。如果您的正则表达式匹配,则它不可能包含除电子邮件以外的任何其他内容。

        【讨论】:

          猜你喜欢
          • 2017-08-24
          • 1970-01-01
          • 1970-01-01
          • 2019-04-15
          • 1970-01-01
          • 1970-01-01
          • 2018-05-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多