Extract email addresses from text string – PHP Script!

We some time  need to extract the email address from a long string or text paragraphs. Lets say we have a long paragraph which is about 3 pages of text and need to get the email addresses in between from the paragraph, it will at least take half an hour to extract all the email address manually.

But with the help of PHP it will only take seconds to extract all of them at one, whether it is few pages or hundreds of pages.

This small PHP script will help us to extract the email address from a long paragraph or text. Just copy paste this script and save it as a PHP file (extract.php):

<?php

$string		=	"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, abcd@test1.com, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. testing@193.32.23.2.com, spiderman@supertesting.com, Nullam dictum felis eu pede mollis pretium. Integer tincidun";

$pattern	=	"/(?:[a-z0-9!#$%&'*+=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/";

preg_match_all($pattern, $string, $matches);

foreach($matches[0] as $email){
	echo $email.", ";
}
?>

The above script will produce this result:

abcd@test1.com, testing@193.32.23.2.com, spiderman@supertesting.com,

 

7 thoughts on “Extract email addresses from text string – PHP Script!”

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top