Recently while building AVLTweetup.com we decided that instead of just displaying the tweets as plain text and making people copy and paste links or hashtags into their address bar that we would just make them automatically link for them. It isn’t much work for us to do that and it saves people who use the site some time. This is pretty easily done using some regular expressions and replacing the pattern with a string we specify. Since Twitter has a well define format all we need to do is look for a few things and switch em out. Here is how we are handling each Tweet as we parse our tree of tweets.
$formatted_text = preg_replace('/(\b(www\.|http\:\/\/)\S+\b)/', "<a target='_blank' href='$1'>$1</a>", $tweet->text); $formatted_text = preg_replace('/\#(\w+)/', "<a target='_blank' href='http://search.twitter.com/search?q=$1'>#$1</a>", $formatted_text); $formatted_text = preg_replace('/\@(\w+)/', "<a target='_blank' href='http://twitter.com/$1'>@$1</a>", $formatted_text);
So this will first replace any links with an actual anchor tag and then we are going to convert all our hash tags to links to searches and all our user tags to links to their page.
Now we have the formatted text from the raw text the Twitter Search API gives us. All we have to do is display it how we want in our layout. Also while printing out the content i made sure to enclose our text in a specified class so it would be easy to find it for the next little bit of code that will go and fetch any twitpics and display them when a user mouses over the url. I will do a full write up on that in the future so that I can walk through the whole process since it will involve css combined with js and some php.
A short post but it has been a while since a fresh post so starting off a bit slow!