代码之家  ›  专栏  ›  技术社区  ›  st4ck0v3rfl0w

Regex:如何在“@”符号前删除电子邮件?

  •  8
  • st4ck0v3rfl0w  · 技术社区  · 15 年前

    我有下面的线

    First Last <first.last@email.com>
    

    我想提取

    "first.last" 
    

    使用regex&php从电子邮件字符串。怎么办?

    事先谢谢!

    6 回复  |  直到 15 年前
        1
  •  5
  •   Erik    15 年前

    我知道答案已经被接受,但这将适用于以下格式的任何有效电子邮件地址: Name <identifier@domain>

    // 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"
    

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

        2
  •  6
  •   ghostdog74    15 年前
    $str ="First Last <first.last@email.com>";
    $s = explode("@",$str);
    $t = explode("<",$s[0]);
    print end($t);
    
        3
  •  3
  •   casraf    15 年前

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

    $email = 'my.name@domain.com';
    $split = explode('@',$email);
    $name = $split[0];
    echo "$name"; // would echo "my.name"
    

    要检查有效性,可以执行以下操作:

    function isEmail($email) {
        return (preg_match('/[\w\.\-]+@[\w\.\-]+\.\[w\.]/', $email));
    }
    if (isEmail($email)) { ... }

    至于从中提取电子邮件 First Last <first.last@domain.com> ,

    function returnEmail($contact) {
        preg_match('\b[\w\.\-]+@[\w\.\-]+\.\[w\.]\b', $contact, $matches);
        return $matches[0];
    }
    
        4
  •  2
  •   No Refunds No Returns    15 年前

    你不能用拆分函数来代替吗?我不使用PHP,但如果它可用的话,这似乎要简单得多。

        5
  •  1
  •   Anon.    15 年前

    如果那是 准确的 将得到的格式,然后与regex进行匹配

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

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

        6
  •  0
  •   Ben Rowe    15 年前

    不需要使用regexp;使用一些简单的字符串函数更有效。

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