简体   繁体   中英

How to get email address from a long string

In PHP, I have a string like this:

$string = "user@domain.com MIME-Version: bla bla bla";

How do i get the email address only? Is there any easy way to get the value??

Building on mandaleeka's answer, break the string up using a space delimeter then use filter_var to sanitize then validate to see if what remains is a legitimate email address:

function extract_email_address ($string) {
    foreach(preg_split('/\s/', $string) as $token) {
        $email = filter_var(filter_var($token, FILTER_SANITIZE_EMAIL), FILTER_VALIDATE_EMAIL);
        if ($email !== false) {
            $emails[] = $email;
        }
    }
    return $emails;
}

If you're not sure which part of the space-separated string is the e-mail address, you can split the string by spaces and use

filter_var($email, FILTER_VALIDATE_EMAIL)

on each substring.

based from constantine regex.. works with ip address domain too.

$pattern="/(?:[A-Za-z0-9!#$%&'*+=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[A-Za-z0-9-]*[A-Za-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/";

//$pattern="/[A-Za-z0-9_-]+@[A-Za-z0-9_-]+\.([A-Za-z0-9_-][A-Za-z0-9_]+)/";

$subject="Hello a@b.com francis a@b words francisfueconcillo@gmail.com words 2 words123 francis@192.168.0.1";


preg_match_all($pattern, $subject, $matches);

Updating @Rob Locken's answers:

function extract_email_address ($string) {
   $emails = array();
   $string = str_replace("\r\n",' ',$string);
   $string = str_replace("\n",' ',$string);

   foreach(preg_split('/ /', $string) as $token) {
        $email = filter_var($token, FILTER_VALIDATE_EMAIL);
        if ($email !== false) { 
            $emails[] = $email;
        }
    }
    return $emails;
}

This small PHP script will help us to extract the email address from a long paragraph or text. Just copy paste this script and save it as a PHP file (extract.php):

$string="user@domain.com MIME-Version: bla bla bla";

$pattern="/(?:[a-z0-9!#$%&'*+=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/";

preg_match_all($pattern, $string, $matches);

foreach($matches[0] as $email){
    echo $email.", ";
}
?>

The above script will produce this result:

user@domain.com,

Email addresses are really tricky to filter using regular expressions because there are so many possible allowable characters. It can be done, but you may have to tweak it some to get exactly what you need.

You could start with something like this:

$string = "user@domain.com MIME-Version: bla bla bla";
$matches = array();
$pattern = '/[A-Za-z0-9_-]+@[A-Za-z0-9_-]+\.([A-Za-z0-9_-][A-Za-z0-9_]+)/'
preg_match($pattern,$string,$matches);

And then $matches should contain your email address.

If the email address is always at the front of the string, the easiest way to get it is simply to split the string on all instances of the space character, and then just take the first value from the resulting array.

Of course, make sure to check it is something resembling an email address before you use it.

See the PHP 'split' function for details.

$text = 'First Last <name@example.com>'
$emails = array_filter(filter_var_array(filter_var_array(preg_split('/\s/', $text), FILTER_SANITIZE_EMAIL), FILTER_VALIDATE_EMAIL));

this worked for me

(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

detect any email address in a string

Have a look at Regular expressions in PHP .

With regular expressions you can identify any text pattern in a given string. They are incredibly useful. So even though you can stick with copy-pasting a code snippet from another answer for now, you should consider digging a little more into it.

It can be a bit complex at first but it's definitely worth the effort.

If it's really space-separated:

php > $matches = array();
php > preg_match('/^[^ ]*/', $string, $matches);
php > print_r($matches[0]);
user@domain.com

匹配正则表达式,如 - ([A-Za-z0-9-]+)@([A-Za-z0-9])\\\\.([az]{3})或类似的东西。

I also modified @Rob Locke's answer. I found that it didnt work for me because I had to first split by commas then by spaces.

function extract_email_addresses($sString)
{
  $aRet = array();
  $aCsvs = explode(',', $sString);
  foreach($aCsvs as $sCsv)
  {
    $aWords = explode(' ', $sCsv);
    foreach($aWords as $sWord)
    {
        $sEmail = filter_var(filter_var($sWord, FILTER_SANITIZE_EMAIL), FILTER_VALIDATE_EMAIL);
        if($sEmail !== false)
            $aRet[] = $sEmail;
    }
  }
  return $aRet;  
}

The following solution is a modified version of https://stackoverflow.com/a/47150078/3010827 that is easier to undestand

$text = 'First Last <name@example.com>';

// split the string into multiple parts base on a space separator
$parts = preg_split('/\s/', $text);

// Sanitize each part by removing invalid email characters. For example <joe.doe@email.com> will become joe.doe@email.com
$parts = filter_var_array($parts, FILTER_SANITIZE_EMAIL);

// Filter out invalid emails  for each part. Valid emails will be kept while invalid ones will be replaced by `false`
$emails = filter_var_array($parts, FILTER_VALIDATE_EMAIL);

// remove `false` values from the array of emails, that's the default behavior of array_filter without the optional callback function
$emails = array_filter($emails);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM