phpstringemail

How to extract Email & Name from Full Email text using PHP?


I have a string as

$email_string='Aslam Doctor <aslam.doctor@gmail.com>';

From which I want to extract Name & Email using PHP? so that I can get

$email='aslam.doctor@gmail.com';
$name='Aslam Doctor'

Thanks in advance.


Solution

  • As much as people will probably recommend regular expression I'd say use explode(). Explode splits the string up in several substrings using any delimiter. In this case I use ' <' as a delimiter to immediately strip the whitespace between the name and e-mail.

    $split = explode(' <', $email_string);
    $name = $split[0];
    $email = rtrim($split[1], '>');
    

    rtrim() will trim the '>' character from the end of the string.