PHP Tip: Replace URLs With Links

I was trawling through the PHP function reference the other day, looking for some information on regular expressions, when I happened across this gem:

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

It may look like gibberish at first, but if you look at it for awhile, you might be able to guess what it does.

Suppose you’re writing a PHP script that displays data, let’s use blog comments as an example. Sometimes the data being displayed may have a URL pasted into it by the user that submitted it. Wouldn’t it be nicer for the end user if URLs like that were automatically turned into clickable links, so “” would become “”

That’s exactly what this line of PHP code does. It takes the variable $text and parses through it, converting stray URLs into clickable links.

  • Bill K

    I've been looking for this for a solid week. Thank you so much!

  • Bill K

    oh but actually its deprecated. damn.

    • redwall_hp

      Oh is it? Well, I'm sure it should be possible to convert the expression to a Perl-style regex and use preg_replace() instead. Maybe I'll work up a new expression and add it here in the future.

  • Jeffrey Bennett

    Wow, you are an absolute lifesaver!! Thank you so much for this script! Works great! :D