Turn Plain Text URLs into Active Links using PHP

Posted on September 3, 2009  |  Category: Tutorials

I was putting together a bit of code to pull in a Twitter feed, similar to what you see in the footer of bavotasan.com. I got everything working properly but the only problem was all of the URLs were just plain text instead of active links. I figured out a way to automatically turn the URLs into active links using a small piece of PHP.

$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a href=\"\\0\">\\0</a>", $text);

The code finds all instances of http:// and converts the string into an active link by surrounding it with an anchor tag.


Tags: , , , , , , , , , , , , ,

Short URL: http://bavotasan.com/?p=983

3 Responses to “Turn Plain Text URLs into Active Links using PHP”

  1. Chris, just as a way to help some of the non-technical people out there you could wrap this code in a simple function and make it a lot easier for them.

    function HyperlinkText($text) {
    return ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"\\">\</a>", $text);
    }

    If people put this function in the bottom of their PHP file, they can now simply call it throughout the code by typing:

    echo HyperlinkText("Your http://thisismyurl.com here.");

    #4155
  2. Kit

    Thx. Great tip.

    #4317
  3. Cool.. But I’ve noticed, that this will not work, if the URL contains parameters.

    Ex:
    http://macknonalds.0fees.net/index.php?para=1&para=2

    Do you have any idea, on how to properly place regex, to accommodate this kind of URL inputs?

    Thanks

    #4715

Leave a Reply

To enter code in the comment box, please place it between <pre lang="php"> </pre> tags. You don't have to convert any characters to their hex/HTML code. Just add your code the way you would to any code editor.