PHP: Convert E-Mail Addresses from a String into Clickable Links

Posted on October 6, 2008, Filled under PHP,  Bookmark it

This is a snippet that finds e-mail addresses from a string using a regexp and converts them into clickable links.

<?php
function convert_emails_to_clickable_links($text)
{
$regex = "([a-z0-9_\-\.]+)". # name

"@". # at

"([a-z0-9-]{1,64})". # domain

"\.". # period

"([a-z]{2,10})"; # domain extension 

$text = eregi_replace($regex, '<a href="mailto:\\1@\\2.\\3">\\1@\\2.\\3</a>', $text);

return $text;
}

$text = 'You can contact me at: example-name@mysite.com. My alternative address is other-username@domain.com.';

echo convert_emails_to_clickable_links($text);

/*
You can contact me at: <a href="mailto:example-name@mysite.com">example-name@mysite.com</a>. My alternative address is <a href="mailto:other-username@domain.com">other-username@domain.com</a>.
?>
*/

Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!

Get our RSS Feed!

Sponsors

One Reply to "PHP: Convert E-Mail Addresses from a String into Clickable Links"

  1. That code won’t pick up any e-mail addresses with capital letters. Use eregi_replace instead of ereg_replace.

Leave a Reply


* = required fields

(will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


  

CommentLuv Enabled