PHP – Make URLs and Twitter Usernames in Text, Links

I have been playing with Twitter’s API lately; I ended up building a Twitter Timeline WordPress widget that displays latest tweets of a given user without you manually creating the twitter widget
I hope to publish the widget on WordPress plugin directory soon.

While building the timeline widget, I needed to make URLs and username mention in a user tweets links because the tweets are plain text when retrieved via the API.

The code snippets below create a click-able link from a URL and Twitter username/handle powered by regular expression where $text variable is the text string.


// make a URL in text link
$result = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $text);

// linkify a twitter username or handle
$$result = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="http://twitter.com/$1">@$1</a>', $text);

In my situation, I needed to perform the above two RegEX search and replace on the twitter tweets.
The code below explains how it can be done.


// store the regex pattern and replacement in array
$patterns = array('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '/@([A-Za-z0-9_]{1,15})/');

$replace = array('<a href="$1">$1</a>', '<a href="http://twitter.com/$1">@$1</a>');

$result = preg_replace($patterns, $replace, $text);

I hope someone find this post useful someday.

Don’t miss out!
Subscribe to My Newsletter
Invalid email address