Sunday, 24 November 2013

Clickable links in your Twitter feed

I recently had a request from a client asking to make the links in their Twitter feed clickable. Now for many developers the first thing that pops into their mind is something like:

"Oh, you're gonna need regex for that..."

Judging by my research on the subject it seems many developers have indeed taken that approach. However, as many will know regex is a pain to maintain - not to mention time consuming to create in the first place. There's usually a performance hit associated to regex too.

The solution? Handily Twitter has this concept of 'Entities' which groups URLs, Hashtags and other such things together. In this post it's URLs we're interested in so I'll stick with that but the code can easily be extended to serve up Hashtags as hyperlinks too.

When you request a feed from Twitter the data you receive contains all sorts of information about each post. Right from the post itself to who replied/retweeted. Within the detail of the tweet you'll find a section containing 'Entities' - as mentioned above, you'll find all the URL's posted in the tweets text. Now here's the really useful part, Twitter also provide the character position within the text where the URL begins and ends - handy, eh? So this is what I used to wrap the URLs in <a> tags and here's my code...


Usage

Note that this is a PHP function but the concept could be converted to any language. If you need help feel free to comment and I'll see what I can do.

Pop this function into your class (maybe called Twitter). Once in place modify the function that obtains your feed and pass the json decoded array to this function, simply:

Twitter::_applyEntities($feed);

Note the function doesn't return anything as you're passing the array by reference. In effect the _applyEntities() function is a modifier/decorator function so there's no need to catch its result. Also, if either the feed is empty or no URLs are found the feed won't be altered in any way.

Final Notes

If you convert my code or use a similar method in a different language please post a comment and I'd be happy to add your Gist to this post - share the wealth!