Extract Email addresses from a webpage – PHP Script!

email-extract

Lets say you have a very long webpage with a lot of text content and email addresses in it, If you want to take out only the email addresses manually, it is not very easy. It will take plenty of your time to extract all of them and there is a chance we miss some of the email addresses!

To avoid such kind of trouble and to save your time, I have written a PHP script which will help you to get what you want!

In this script I’m using regular expression to extract the email addresses, here is the pattern:

<?php

$pattern	=	"/(?:[a-z0-9!#$%&'*+=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+=?^_`{|}~-]+)*|"(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-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-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])/ ";

?>

The above regex pattern will extract all kind of email addresses even with IP address like (superscript@192.168.1.1.com).
So, here is the entire HTML and PHP part, just copy this file and save it as (anyname.php):

<html>
<body>
	<h2>Extract the email from a webpage using PHP Script - Tutorial by <a href="https://blog.theonlytutorials.com">Blog.theonlytutorials.com</a></h2>
	<form action="" method="post">
		URL: <input type="text" name="url" />
	</form>
</body>
</html>

<?php

if(isset($_POST['url'])){

	//extract the content using file_get_contents()
	$string = file_get_contents($_POST['url']);

	//reg ex pattern to extract email
	$pattern	=	"/(?:[a-z0-9!#$%&'*+=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+=?^_`{|}~-]+)*|"(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-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-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])/ ";

	//check if email is found
	$check_if_email = preg_match_all($pattern, $string, $matches);

	$allemails = '';

	//if email found then loop
	if($check_if_email != 0){
		foreach($matches[0] as $email){
			$allemails .= $email.", ";
		}
	}else{
		echo "No emails found";
	}
	echo "<textarea style='margin: 2px; height: 194px; width: 620px;'>$allemails</textarea>";

}

?>

The above script uses file_get_contents() to read the webpage. Your server should be enabled allow_url_fopen() function otherwise you may need to use CURL to read the webpage.

For your convenience I have given a Demo here:

demo

One thought on “Extract Email addresses from a webpage – PHP Script!

Leave a Reply

Theme: Overlay by Kaira
Agurchand