Find and Replace Hyperlinks and Email Addresses in PHP

A note from A Beautiful Site’s founder: We developed Surreal to be easy for you and your clients. If you’re a web designer, you should take a look at the simple, hosted CMS that’s changing the way content is managed. Surreal integrates in moments and is trusted by over 18,000 websites. Try it out for free and let us know what you think! Visit Website »

These two PHP functions use regular expressions to add the appropriate HTML anchor tags around hyperlinks and email addresses in $string.

PHP Code

function parseHyperlinks($string) {
    // Add <a> tags around all hyperlinks in $string
    return ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"\\0\">\\0</a>", $string);
}

function parseEmails($string) {
    // Add <a> tags around all email addresses in $string
    return 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);
}

Output

Using parseHyperlinks(), http://domain.com/index.htm becomes:

<a href="http://domain.com/index.htm">http://domain.com/index.htm</a>

And using parseEmails(), email@domain.com becomes:

<a href="mailto:email@domain.com">email@domain.com></a>
If you enjoyed this article, please share it with a friend!

5 Responses to Find and Replace Hyperlinks and Email Addresses in PHP

  1. Gavin says:

    This doesn’t correctly parse e-mail addresses with mixed character case, i.e. myEmail@domain.com.

  2. Cory LaViska says:

    Gavin, good catch. I adjusted the regex to support both upper and lowercase.

  3. giu says:

    thank you very much. beautifuly code and very useful. will use both functions in my twitter-plugin for wordpress, which I will release in the next few days. needless to say, I will mention you in the about-page and in the source code :) have a nice weekend and keep up the good work!

  4. Adrian says:

    Thank you very much! I used this code for my website… http://www.myiptest.com

  5. kushal says:

    how can we do the reverse of this?? Can anybody help me into this?

Leave a Reply

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

*

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