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

7 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
  4. I know you are showing a general way to do this for any PHP project, but thought people might want to know the best way to do this in WordPress specfically. There is a function called make_clickable() that you can use. http://codex.wordpress.org/Function_Reference/make_clickable

    #8079
    • Actually, in WordPress 2.9 there is an option to automatically embed all plain text URLs. Check out the Media admin page under the Settings panel.

      #8088
  5. Nice, thanks. Hadn’t noticed that new option. I don’t want to take this off topic too far, but do you have a good replace function to force external URL’s to open in a new browser tab? i.e. find all the URL’s and check whether they already have a target=”" parm on them and if not set target=”whatever”?

    #8145

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.