Making Twitter @Username Clickable in Sweetcron

by keif on May 31, 2009

I’m a fan of Yongfook’s work, particularly Sweetcron.

What is Sweetcron?

To quote Wikipedia:

Sweetcron is an open source lifestreaming blog software created by Jon “Yongfook” Cockle based on the CodeIgniter framework. It was originally released on 3 September 2008 and the latest version following on 22 September. Sweetcron is similar to other web applications such as Tumblr and Friendfeed, but users are able to host their own lifestream on their own server and customize it in any way they want with the Sweetcron API.

Users can add RSS feeds from multiple social networks and sites, such as Twitter, LastFM, Flickr and many more.

Basically, if it has an RSS feed, you can utilize it to create your own personal lifestream.

How can I make those @Usernames clickable?

Sometimes, the code can get lost in translation. Maybe it’s your RSS feed, maybe it’s the provider, hell, mabe it’s Sweetcron. But Sweetcron gives you two handy methods to manipulate your data in two handy “plug-in functions“:

  • function pre_db: before you store the information in the database.
  • function pre_display: after it’s been saved to the database, but before it’s rendered.

Thanks to regular expressions, we can loop through information before we save it to our database, or afterwards, depending on your preference. All you need is:
[code lang="php"]
// change @names into clickable links
$item->item_title = preg_replace('/(^|[^\w])(@[\d\w\-]+)/', '<a href="http://twitter.com/$2">$2</a>' ,$item->item_title);
[/code]

$item represents your sweetcron’d “post” which consists of the object – code, text, images, links, etc. We’re basically saying “in this object, there is an item_title, if it has @something, make it a link that points to user @something” – simple enough, eh?

  • There is a small error in the regex, the output was http://twitter.com/@username, however those usernames do not exist. I have modified it to create the correct link:
    [code]
    $item->item_title = preg_replace('/(^|[^\w])@([\d\w\-]+)/', '@$2' ,$item->item_title);
    [/code]
  • Awesome, thank you! I'll update the post as soon as I can.
blog comments powered by Disqus

Previous post: Posting to Twitter Using PHP and cURL

Next post: MooTools Development in Dojo Land