Usernames and hashtag links in Twitter API

You’ll probably have noticed if you’re using the Twitter API that when you get the text of the tweet you don’t get any of the @usernames or #hashtags, or even URLs converted to actual links. It doesn’t look like a lot of the libraries (for PHP at least) bother with doing that either.

Here’s the code to get it to do that though:

<?php
$twitter_user = "shamess";

$json = file_get_contents ("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=".$twitter_user."&count=3&trim_user=true");
$tweets = json_decode ($json);

foreach ($tweets as $tweet) {
 // change all the urls to links
 $tweet_text = preg_replace ("/http://(S+)/i", "<a href="http://$1">http://$1</a>", $tweet->text);
 // @usernames
 $tweet_text = preg_replace ("/@(w+)/", "<a href="http://twitter.com/$1">@$1</a>", $tweet_text);
 // #hashtags too
 $tweet_text = preg_replace ("/#(w+)/", "<a href="http://twitter.com/search?q=$1">#$1</a>", $tweet_text);

 echo "<li>".$tweet_text." - <em><a href="http://twitter.com/shamess/status/".$tweet->id_str."">".date ('l at H:i', strtotime ($tweet->created_at))."</a></em></li>n";
}

Twitter and politics

John Prescott decided to write an article commenting on how politicians use social media, off the back of Cameron’s “twat” remark. He said that having to get your point across in 140 characters forces them to be concise and to have an actual opinion, not avoid the question.

One of the comments to his article was

Yeah, more empty sloganeering is exactly what the country needs.

thaumaturge

And I can see their point. The example that Prescott gave – “tough on crime, tough on the causes of crime” – was a bad one. That’s not really the use of twitter.

Cameron apologises for saying offensive 4 letter word on radio – TORY? http://tinyurl.com/mtd6sj

@johnprescott

That’s more like a twitter usage. It’s not a party policy message because there’re better places for those to go. The limited characters really isn’t enough for those. But a quick quip, off the cuff, makes the politician more human. Someone we can relate to better and get to know on a more personal level.

I want more politicians to be using the Internet like this. You can have an actual conversation with them on twitter and sometimes they even reply. People have to remember, and respect, that you’re voting for an actual person, not a party. Just because a person is a member of the Labour party, it doesn’t mean they back national ID cards, for instance. Voters need to know who the person is, not just what party they’re in.

As always where politics is concerned, people are idiots. The comments to that article could have been a nice debate about the uses of the Internet within our executive, but instead they turned mostly into people complaining about Labour. The damn article had nothing to do with Labour. STFU.