【问题标题】:Regex: How to strip email before "@" symbol?正则表达式:如何在“@”符号之前删除电子邮件?
【发布时间】:2011-01-20 08:33:52
【问题描述】:

我有以下字符串

First Last <first.last@email.com>

我要提取

"first.last" 

来自使用正则表达式和 PHP 的电子邮件字符串。这个怎么办?

提前致谢!

【问题讨论】:

  • 在查看答案时,您可能需要注意"e\@w"@example.com 在技术上是一个有效的电子邮件地址。
  • 刚刚意识到字符串不仅仅是电子邮件地址。
  • 您可能会发现 s($str)-&gt;beforeLast('@') 很有帮助,如在 this standalone library 中找到的。

标签: php regex string


【解决方案1】:

这要容易得多(在检查电子邮件是否有效之后):

$email = 'my.name@domain.com'; $split = explode('@',$email); $name = $split[0]; 回声“$名称”; // 会回显“my.name”

要检查有效性,您可以这样做:

功能是电子邮件($电子邮件){ return (preg_match('/[\w\.\-]+@[\w\.\-]+\.\[w\.]/', $email)); } if (isEmail($email)) { ... }

至于从First Last &lt;first.last@domain.com&gt;中提取邮件,

函数 returnEmail($contact) { preg_match('\b[\w\.\-]+@[\w\.\-]+\.\[w\.]\b', $contact, $matches); 返回 $matches[0]; }

【讨论】:

    【解决方案2】:

    我知道答案已被接受,但这适用于任何有效的电子邮件地址,格式为:Name &lt;identifier@domain&gt;

    // Yes this is a valid email address
    $email = 'joey <"joe@work"@example.com>';
    
    echo substr($email, strpos($email,"<")+1, strrpos($email, "@")-strpos($email,"<")-1);
    // prints: "joe@work"
    

    大多数其他已发布的解决方案在一些有效的电子邮件地址上都会失败。

    【讨论】:

      【解决方案3】:

      无需使用正则表达式;使用一些简单的字符串函数效率更高。

      $string = 'First Last <first.last@email.com>';
      $name = trim(substr($string, 0, strpos($string, '<')));
      

      【讨论】:

      • 除非您的结果是“First Last”,而不是“first.last”
      【解决方案4】:
      $str ="First Last <first.last@email.com>";
      $s = explode("@",$str);
      $t = explode("<",$s[0]);
      print end($t);
      

      【讨论】:

      • Ghostdog,我也喜欢这个解决方案,但公平地说,我的问题要求使用正则表达式。不过,您的解决方案效果很好,感谢您的回复!
      • 顺便说一句,print end() 是做什么的?
      • 很公平。这是你的选择。我只是为您的特定字符串示例提供了一个更简单的替代方案。 end($t) 是数组的最后一个元素。查看 PHP 文档了解更多
      【解决方案5】:

      如果这是您将获得的 exact 格式,则与正则表达式匹配

      /<([^@<>]+)@([^@<>]+)>/
      

      会给你例如first.last 在捕获组 1 中,email.com 在捕获组 2 中。

      【讨论】:

      • 请注意,这会阻塞包含多个 @s 的电子邮件地址。不过,我怀疑这对绝大多数用户来说是个问题——在这种情况下,一个在 99.9% 的时间内有效的解决方案只需要不到 0.1% 的工作量就可以让最后 0.1% 的工作正常工作。
      【解决方案6】:

      您不能只使用拆分功能吗?我不使用 PHP,但如果它可用,这似乎会简单得多。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-11-30
        • 1970-01-01
        • 2012-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多