Extract email addresses from a string – PHP

0 min read 79 words

Sometimes you need to extract multiple email addresses from a string and the following function will make all your dreams come true.

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

..and this is how you use it:

$text = "this is some text and here is an email address [email protected], here's another [email protected], etc..";
$emails = extract_emails_from($text);

Now let’s use the data:

// as string
print(implode("\n", $emails));

// loop as array
foreach($emails as $email) {
    echo $email .",";
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags