How To Extract Email Addresses From a String in PHP

Reading Time: 3 minutes

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.


$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:, valid email:, 
           invalid email: test2@^, valid email:, 
           invalid email: test4@";

// 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>";


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.


Your project URL will be like this.

URL: http://localhost/php-emails/index.php

We hope this article helped you to learn How To Extract Email Addresses From a String in PHP Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

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.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more