Linkify Your Twitter Feed

Written by David Walsh on January 26, 2009 · 24 Comments
This post was authored by Jeremy Parrish. To learn more about Jeremy, click here.

So, you want to display your Twitter status on your blog? No problem, use the API. But, what if you want to display links in your status like twitter.com itself does? No problem, use regular expressions.

Here is a function that will turn all HTTP URLs, Twitter @usernames, and #tags into links:

The PHP

function linkify_twitter_status($status_text)
{
  // linkify URLs
  $status_text = preg_replace(
    '/(https?:\/\/\S+)/',
    '<a href="\1">\1</a>',
    $status_text
  );

  // linkify twitter users
  $status_text = preg_replace(
    '/(^|\s)@(\w+)/',
    '\1@<a href="http://twitter.com/\2">\2</a>',
    $status_text
  );

  // linkify tags
  $status_text = preg_replace(
    '/(^|\s)#(\w+)/',
    '\1#<a href="http://search.twitter.com/search?q=%23\2">\2</a>',
    $status_text
  );

  return $status_text;
}

Using It

There are many ways to grab statuses from Twitter. Here, I will show a very simple method with no caching -- suitable for demonstration purposes. Feel free to substitute your favorite Twitter-fetching method.

$url = 'http://twitter.com/statuses/user_timeline/davidwalshblog.json?count=1';
$json = file_get_contents($url);
$statuses = json_decode($json);
$status_text = $statuses[0]->text;

echo "before: ", $status_text, "\n";
echo "after: ", linkify_twitter_status($status_text), "\n";

The above code turns:

@davidwalshblog: Check it out http://is.gd/hd2D #awesome
..into:
@<a href="http://twitter.com/davidwalshblog">davidwalshblog</a>: Check it out <a href="http://is.gd/hd2D">http://is.gd/hd2D</a> #<a href="http://search.twitter.com/search?q=%23awesome">awesome</a>

Pretty simple, eh?

About Jeremy Parrish

Jeremy Parrish is the Systems Administrator for Econoprint, a print/design/web company in Verona, Wisconsin. He has a BS in Computer Engineering and Computer Science from the University of Wisconsin--Madison. In his spare time he enjoys running marathons with his wife and working on various coding projects. You can check out Jeremy's blog at http://rrish.org/.

Comments

  1. Great article!

  2. Hey David!

    This works just fantastic. Took like 2 mins for me to impliment it into my website and I am a total php beginner!

    Thank you so much!

    Cheers from Bonn, germany,
    Oliver

  3. Hi Oliver,

    I’m glad it worked for you. It’s nice when you can add something useful in just 2 minutes!

  4. Exactly what I’ve been looking for actually. Thanks :)

  5. Nice work Jeremy. Nice to see someone putting Regexs to good use!

  6. Hi, i think @Luke’s website contains a trojan in his favicon.ico file. Check it.

  7. Wow, I needed this. Thanks a lot.

  8. Jeremy!

    Thank you so much. I have been searching and searching for any easy way to do this that was not already buried in a wordpress plugin or some other place where there were a bunch of extras I didn’t need. All I wanted was to call a simple function passing username and the number of statuses to echo.

    I combined all your stuff and wrote a function called get_Tweets() . It takes $username and $count as variables, loops through the count and echos $count number of statuses as LI elements. So simple, yet I couldn’t find the starting point anywhere!

    To include it with the wordpress theme I am building, I just stuck the finished function in my functions.php file then called get_Tweets(‘USERNAME’, ‘COUNT’) between a UL tag.

    I wanted to include a copy of the code in here, but it didn’t seem to want to let me include the php and it looked a little confusing.

    I would be happy to share with anyone who is interested.

    Thanks again, Jeremy!

    Going to subscribe to your RSS and check out the rest of your site.

    Marty

  9. @Marty: Thanks for the note. I’m glad you found it useful! If you want, you could probably throw your code up on David’s pastebin and throw a link back here in the comments. It sounds like it might be useful for others.

  10. I’ve created a wordpress plugin that will automatically create tag and user links in your posts/pages/comments when #tagname or @username are used… However, I’ve just noticed an issue. When the function runs hooked to “the_content()” if you have any inline styles (color=”#ab0000;”) then the colors are assumed to be tags since they have the pound symbol in front of them.

    Is there a way to make the regex differentiate between css color codes and tags you insert?

  11. @Josh: The function should really only be passed the actual tweet text, without any container markup. However, if you can assure that there is no whitespace character immediately preceding the ‘#’ character (e.g. “color:#ab0000;”), you should be OK. I still wouldn’t recommend using it that way, though.

  12. Any idea on why I’m getting a “Fatal error: Call to undefined function: json_decode()”? I’m running PHP 5.2.9 so I believe this function would be in there.

  13. Thank you so much for creating this! I’ve got everything else sorted for a little Twitter App I’m working on, but I have no clue when it comes to Regex in PHP, so this is perfect!

  14. Thanks!!
    Save my day…

  15. sdesocio April 6, 2010

    Im kind of a dummy with this stuff but I thought I was supposed to put everything inside of the function.php file, but that doesnt seem to work.

  16. What about URLs that contain hash characters? Won’t the part of the URL after the tag get linkified as a hashtag?

  17. thank you very much. i have been searching for this for two days and could not find any solutions. but luckily i see this and done in 10 minutes.

  18. Great article. Thanks. Helped me.

  19. Orun Bhuiyan August 2, 2013

    Thanks for the regexp!

  20. Hi David,

    i use your code and this code to display feeds on my page $this->linkify($feed_item->text) and I have small problem if you can help? The result is Twitter results feedhttp://t.co/F6xyyR9Ee7 and I would like to be like this Twitter results feed. can you help me? Any idea how I could do? Thank you very much

  21. i write code result again:

    this is the result:
    Twitter results feed http://t.co/F6xyyR9Ee7
    and i want to be like this
    Twitter results feed
    basically want “Twitter results feed” to be inside of tag

    • Robert:

      replace this:

      $status_text = preg_replace(
      ‘/(https?:\/\/\S+)/’,
      ‘\1‘,
      $status_text
      );
      

      with this:

      $status_text = preg_replace(
      ‘/(https?:\/\/\S+)/’,
      ‘Twitter results feed‘,
      $status_text
      );
      
    • Sorry, my code pasted wrong.

      I meant to say replace the “\1″ with whatever text you want the link to be in the second parameter of the preg_replace function

Be Heard

Tip: Wrap your code in <pre> tags or link to a GitHub Gist!

Use Code Editor
Older
google.load(): Utilize Google's AJAX Libraries API
Newer
Implementing jQuery-Like Event Syntax in MooTools