PHP: extract email addresses from string

2016-10-20 00:00:00 IN1 , 2023-04-10 14:16:29 IN1


this function searches for email adresses inside a String and returns an array containing the adresses. Thanks to unicode parsing it can detect those with umlauts also.

<?php

/**
 * search for email adresses, returns them as array
 * @access public
 * @param string $sString String to search in
 * @return array $aMatch
 */
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 = 'foo@example.com XXX bar@example.com XXX <baz@example.com>';

$aEmail = getEmailArrayFromString($sString);

/**
 * array(3) {
    [0]=>
        string(15) "foo@example.com"
    [1]=>
        string(15) "bar@example.com"
    [2]=>
        string(15) "baz@example.com"
    }
*/
var_dump($aEmail);
This website uses Cookies to provide you with the best possible service. Please see our Privacy Policy for more information. Click the check box below to accept cookies. Then confirm with a click on "Save".