从字符串中提取电子邮件地址 - php

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33865113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:38:45  来源:igfitidea点击:

Extract email address from string - php

php

提问by Liz.

I want to extract email address from a string, for example:

我想从字符串中提取电子邮件地址,例如:

<?php // code
$string = 'Ruchika <[email protected]>';
?>

From the above string I only want to get email address [email protected].

从上面的字符串中,我只想获取电子邮件地址[email protected]

Kindly, recommend how to achieve this.

请推荐如何实现这一目标。

回答by Niranjan N Raju

Try this

尝试这个

<?php 
    $string = 'Ruchika < [email protected] >';
    $pattern = '/[a-z0-9_\-\+\.]+@[a-z0-9\-]+\.([a-z]{2,4})(?:\.[a-z]{2})?/i';
    preg_match_all($pattern, $string, $matches);
    var_dump($matches[0]);
?>

see demo here

在这里演示

Second method

第二种方法

<?php 
    $text = 'Ruchika < [email protected] >';
    preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $text, $matches);
    print_r($matches[0]);
?>

See demo here

在这里查看演示

回答by Jacques

Parsing e-mail addresses is an insane work and would result in a very complicated regular expression. For example, consider this official regular expression to catch an e-mail address: http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html

解析电子邮件地址是一项疯狂的工作,会导致非常复杂的正则表达式。例如,考虑使用这个官方正则表达式来捕获电子邮件地址:http: //www.ex-parrot.com/pdw/Mail-RFC822-Address.html

Amazing right?

很惊人吧?

Instead, there is a standard php function to do this called mailparse_rfc822_parse_addresses()and documented here.

相反,有一个标准的 php 函数可以执行此操作,mailparse_rfc822_parse_addresses()在此处进行了记录

It takes a string as argument and returns an array of associative array with keys display, address and is_group.

它接受一个字符串作为参数并返回一个关联数组的数组,键为 display、address 和 is_group。

So,

所以,

$to = 'Wez Furlong <[email protected]>, [email protected]';
var_dump(mailparse_rfc822_parse_addresses($to));

would yield:

会产生:

array(2) {
  [0]=>
  array(3) {
    ["display"]=>
    string(11) "Wez Furlong"
    ["address"]=>
    string(15) "[email protected]"
    ["is_group"]=>
    bool(false)
  }
  [1]=>
  array(3) {
    ["display"]=>
    string(15) "[email protected]"
    ["address"]=>
    string(15) "[email protected]"
    ["is_group"]=>
    bool(false)
  }
}

回答by julianm

This is based on Niranjan's response, assuming you have the input email enclosed within < and > characters). Instead of using a regular expression to grab the email address, here I get the text part between the < and > characters. Otherwise, I use the string to get the entire email. Of course, I didn't make any validation on the email address, this will depend on your scenario.

这是基于 Niranjan 的回复,假设您将输入电子邮件包含在 < 和 > 字符中)。在这里我没有使用正则表达式来获取电子邮件地址,而是获取 < 和 > 字符之间的文本部分。否则,我使用字符串来获取整个电子邮件。当然,我没有对电子邮件地址进行任何验证,这取决于您的情况。

<?php 
    $string = 'Ruchika <[email protected]>';
    $pattern = '/<(.*?)>/i';

    preg_match_all($pattern, $string, $matches);
    var_dump($matches);
    $email = $matches[1][0] ?? $string;
    echo $email;
?>

Here is a forked demo.

这是一个分叉的演示

Of course, if my assumption isn't correct, then this approach will fail. But based on your input, I believe you wanted to extract emails enclosed within < and > chars.

当然,如果我的假设不正确,那么这种方法就会失败。但是根据您的输入,我相信您想提取 < 和 > 字符中包含的电子邮件。

回答by Priya Rajaram

try this code.

试试这个代码。

<?php

function extract_emails_from($string){
  preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $string, $matches);
  return $matches[0];
}

$text = "blah blah blah blah blah blah [email protected]";

$emails = extract_emails_from($text);

print(implode("\n", $emails));

?>

This will work.

这将起作用。

Thanks.

谢谢。

回答by katwekibs

This will work even on subdomains. It extracts all emails from text.

这甚至适用于子域。它从文本中提取所有电子邮件。

$marches[0]has all emails.

$marches[0]有所有电子邮件。

$pattern = "/[a-zA-Z0-9-_]{1,}@[a-zA-Z0-9-_]{1,}(.[a-zA-Z]{1,}){1,}/";
preg_match_all ($pattern , $string, $matches);
print_r($matches);

$marches[0]has all emails.

$marches[0]有所有电子邮件。

Array
(
    [0] => Array
        (
            [0] => [email protected]
            [1] => **********@******.co.za.com
            [2] => [email protected]
            [3] => [email protected]
            [4] => [email protected]
        )

    [1] => Array
        (
            [0] => .com
            [1] => .com
            [2] => .com
            [3] => .com
            [4] => .com
        )

)

回答by Janith Chinthana

Found some useful codesas bellow,

找到了一些有用的代码,如下所示,

<?php
    // input: My Test Email <[email protected]>

    function get_displayname_from_rfc_email($rfc_email_string) {
        // match all words and whitespace, will be terminated by '<'
        $name = preg_match('/[\w\s]+/', $rfc_email_string, $matches);
        $matches[0] = trim($matches[0]);
        return $matches[0];
    }
    // Output: My Test Email

    function get_email_from_rfc_email($rfc_email_string) {
        // extract parts between the two parentheses
        $mailAddress = preg_match('/(?:<)(.+)(?:>)$/', $rfc_email_string, $matches);
        return $matches[1];
    }
    // Output: [email protected]
?>

Hope this will help to someone.

希望这会对某人有所帮助。

回答by Guido K.B.W. üffing

use (my) function getEmailArrayFromStringto easily extract email adresses from a given string.

使用 (my) 函数 getEmailArrayFromString可以轻松地从给定的字符串中提取电子邮件地址。

<?php

function getEmailArrayFromString($sString = '')
{
    $sPattern = '/[\._\p{L}\p{M}\p{N}-]+@[\._\p{L}\p{M}\p{N}-]+/u';
    preg_match_all($sPattern, $sString, $aMatch);
    $aMatch = array_keys(array_flip(current($aMatch)));

    return $aMatch;
}

// Example
$sString = '[email protected] XXX [email protected] XXX <[email protected]>';

$aEmail = getEmailArrayFromString($sString);

/**
* array(3) {
    [0]=>
        string(15) "[email protected]"
    [1]=>
        string(15) "[email protected]"
    [2]=>
        string(15) "[email protected]"
    }
*/
var_dump($aEmail);

回答by Chandra Mani Pandey

you can also try:

你也可以尝试:

email=re.findall(r'\S+@\S+','[email protected]')
print email

where \Smeans any non-whitespace character

where\S表示任何非空白字符