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 a
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.
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,
Match to a regular expression like - ([A-Za-z0-9-]+)@([A-Za-z0-9])\\.([a-z]{3})
or something similar.
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;
}
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;
}
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.