How to extract email addresses from a string in 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <?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"; // 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: test@example.com test1@example.org test3@example.co.in |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <?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(); } $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] => test@example.com [1] => test1@example.org [2] => test3@example.co.in ) |
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂