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=””></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 “http://google.com” would become “http://google.com?”

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.

Reminder: Update Your Copyright Notice

WordPress 2.7 Favorites Menu Manager Plugin

BlogBuzz January 3, 2009

WP125 Patch 1.2.1 Released

Best of 2008

PHP strtotime() Function

Skitch: Easy Screenshots and Annotations

WP125 1.2.0 Released

How to Keep AdBlock From Hiding Your Ads