Critique My Regex

Programming 8 March 2010 | 0 Comments

I’m using TwitterLibPHP on my band’s website to display the five most recent tweets from the band Twitter account in the page header. I’m also using the JQuery Cycle plug-in to rotate the tweets randomly. This is all well and good. I wanted to wrap any links in tweets pulled from the Twitter feed with anchor tags so they would be clickable.

I hacked this out in about five minutes:

$pattern = '/(http\S+)/';
$replacement = '<a href="${1}">${1}</a>';
$text = preg_replace($pattern, $replacement, $status->text);
echo $text;

I know this is a really quickie way of testing for URLs with regular expressions and I’m sure it fails a huge number of URLs. It only really needs to work with Bit.ly style “url-shorteners” since the links in the tweets are always converted to small URLs (seeing as I post them with TweetDeck, which does it automatically).

Anyhow, I just thought I’d post it here in case it was useful to someone else, and in case some enterprising Regex wizard decided to give me some constructive criticism.

Leave a Reply