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

Posted on October 6, 2008, 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!

2 Replies 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.

  2. The “eregi_replace” is obsolete so I suggest you change it with “preg_replace” as follows :

    $text = preg_replace ($regex, \ \ 1 @ \ \ 2. \ \ 3 ‘, $text);

    Not to forget to change “$regex” as follows:

    $regex = “/ ([a-z0-9_ \ - \ .]+)”. # name
    “@”. # at
    “([a-z0-9-] {1.64}).” # domain
    “\.”. Period #
    “([az] {# 2.10 })/”; domain extension

    good day

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>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)