Clue Mediator

How to extract email addresses from a string in PHP

📅January 7, 2021
🗁PHP

Today we’ll explain to you how to extract email addresses from a string in PHP.

At some point, we need to extract an email address from a long text string so here we will explain to you an easy way to fetch an email from a long string or paragraph using PHP.

Using the preg_match() or preg_match_all() function, we can get an email address from a string.

Let’s start with an example. For understanding, we have taken an easily understandable paragraph in the following code.

<!--?php
$string = "This is test strings:
valid email: [email protected],
valid email: [email protected],
invalid email: test2@^example.com,
valid email: [email protected],
invalid email: test4@ example.net";<p-->

// pattern for check an email
$pattern = "/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i";

// search matches using preg_match_all() method
preg_match_all($pattern, $string, $matches);

// list of the email addresses
foreach($matches[0] as $email) {
  echo $email."<br>";
}
?>

// Output:
[email protected]
[email protected]
[email protected]

Now, we will write a script using a function that extracts the email addresses from a string and returns an array of an email address.

<!--?php
function extract_emails($str) {
    $pattern = '/([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
    preg_match_all($pattern, $str, $matches);
    // if a match is found then add it to $matches and return it, otherwise return an empty array
    return isset($matches[0]) ? $matches[0] : array();
}<p-->

$string = "This is test strings:
valid email: [email protected],
valid email: [email protected],
invalid email: test2@^example.com,
valid email: [email protected],
invalid email: test4@ example.net";

// array of the email addresses
echo "<pre>";
print_r(extract_emails($string));
?>

// Output:
Array
(
    [0] => [email protected]
    [1] => [email protected]
    [2] => [email protected]
)


<p>That’s it for today.<br>Thank you for reading. Happy Coding..!! 🙂</p>
<!-- /wp:html --></pre>