Inside this article we will see the concept i.e How To Extract Email Addresses From a String in PHP. Article contains the classified information i.e Fetch Email Addresses From a Given String.
At some point, you need to extract an email address from a long text string. Here, you will learn 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.
Read More: How To Enable CORS for Multiple Domains in PHP
Let’s get started.
Application Programming
Let’s create a folder with name php-emails in your localhost directory. In this project folder, create a file: index.php
Open index.php file and write this complete code into it.
<?php $string = "This is a Test String. We have many emails in this string. Some of them are valid and some are invalid. Email example 1: test@example.com, valid email: test1@example.org, invalid email: test2@^example.com, valid email: test3@example.co.in, 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>"; }
Concept
Use a email pattern to find in string.
$pattern = "/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i";
You can get all emails using above pattern and PHP function i.e preg_match_all($pattern, $string, $matches);
Read More: How To Show and Hide Password Field Text Using jQuery
Application Testing
Open your browser.
Next,
Your project URL will be like this.
URL: http://localhost/php-emails/index.php
test@example.com
test1@example.org
test3@example.co.in
We hope this article helped you to learn How To Extract Email Addresses From a String in PHP Tutorial in a very detailed way.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.