Convert an email into link from text in PHP



In some websites, when we add comment with email then email automatically converts into a link, So today I am showing you how to convert an email into link from text in PHP.

$string = 'please contact me on email@emaildomain.com';
ereg_replace("[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,3})", "<a href=\"mailto:\\0\">\\0</a>", $string);

As ereg_replace() is deprecated in PHP 5.3 you should use preg_replace like below:

function convertEmailToLinks($string) {
	return preg_replace("/[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,3})/", "<a href=\"mailto:\\0\">\\0</a>", $string);
}

Now you can use above function like below:

 echo convertEmailToLinks($string); 

And output will be:

 please contact me on <a href="mailto:email@emaildomain.com">email@emaildomain.com</a>