【问题标题】:remove plus symbol from email regex php [closed]从电子邮件正则表达式 php 中删除加号 [关闭]
【发布时间】:2018-02-05 14:38:42
【问题描述】:

我想从电子邮件中删除 + 符号,请帮我写一个不接受电子邮件中 ​​+ 符号的正则表达式。

abc@xyz.com - valid email
abc123@xyz.com - valid email
abc.def@xyz.com - valid email
abc+123@xyz.com - Invalid email

【问题讨论】:

  • ^[^@+]+@\S+$ 可能会 - 问题仍然存在:为什么? + 完全有效。
  • 我正在使用正则表达式进行电子邮件验证,它不接受带有 + 号的电子邮件,并且通过错误 str_replcae 在这里没有用处
  • @Jan 得到错误未知修饰符'@'
  • @codex 为您的模式使用不同的分隔符。将其包裹在/
  • 例如~ 作为分隔符。 @ctwheels

标签: php regex preg-match


【解决方案1】:

根据我的评论,您可能会使用

^[^@+]+@\S+$
# start of line, anything not + or @ 1+ times, followed by @,
# not whitespaces and the end of the string

使用例如~ 作为分隔符并查看 a demo on regex101.com - 问题是:为什么? + 完全有效。

【讨论】:

    【解决方案2】:

    加号是有效的电子邮件字符。

    你标记了这个php。您不应该在 PHP 中使用正则表达式进行电子邮件验证。你应该使用filter_var()

    例子:

    filter_var('bob@example.com', FILTER_VALIDATE_EMAIL);
    

    【讨论】:

      【解决方案3】:

      正则表达式^[^@+]+@[^@]+$

      [^@+] 中添加不需要的字符。

      详情:

      • ^ 在行首断言位置
      • [^]匹配列表中不存在的单个字符
      • + 匹配一次到无限次
      • $ 在行尾断言位置

      PHP 代码

      $strings=['abc@xyz.com','abc123@xyz.com','abc.def@xyz.com','abc+123@xyz.com'];
      
      foreach($strings as $string){
          $match = preg_match('~^[^@+]+@[^@]+$~', $string);
          echo ($string . ' ' . ($match ? 'true' : 'false')."\n");
      }
      

      输出:

      abc@xyz.com true
      abc123@xyz.com true
      abc.def@xyz.com true
      abc+123@xyz.com false
      

      【讨论】:

        猜你喜欢
        • 2013-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-30
        • 2011-01-20
        • 2017-07-05
        • 2012-01-12
        • 1970-01-01
        相关资源
        最近更新 更多