O'Reilly

Linkify Your Twitter Feed

By on  
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/.

Track.js Error Reporting

Recent Features

  • Create Namespaced Classes with MooTools

    MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does.  Many developers create their classes as globals which is generally frowned up.  I mostly disagree with that stance, but each to their own.  In any event,...

  • Facebook Open Graph META Tags

    It's no secret that Facebook has become a major traffic driver for all types of websites.  Nowadays even large corporations steer consumers toward their Facebook pages instead of the corporate websites directly.  And of course there are Facebook "Like" and "Recommend" widgets on every website.  One...

Incredible Demos

  • CSS Background Animations

    Background animations are an awesome touch when used correctly.  In the past, I used MooTools to animate a background position.  Luckily these days CSS animations are widely supported enough to rely on them to take over JavaScript-based animation tasks.  The following simple CSS snippet animates...

  • The Simple Intro to SVG Animation

    This article serves as a first step toward mastering SVG element animation. Included within are links to key resources for diving deeper, so bookmark this page and refer back to it throughout your journey toward SVG mastery. An SVG element is a special type of DOM element...

Discussion

  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. crises

    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. Pedro

    Thanks!!
    Save my day…

  15. sdesocio

    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. RJ

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

  17. Shahid

    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. Dharma

    Great article. Thanks. Helped me.

  19. Orun Bhuiyan

    Thanks for the regexp!

  20. robert

    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. robert

    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

    • Nick

      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
      );
      
    • Nick

      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

      https://gist.github.com/anonymous/9237526

  22. <?php
    function linkify($text) {
    	$search = array("/[\w]+\:\/\/([\w-?&;#~=\.\/\@]+[\w\/])/",
    					"/#([\p{L}]+)/",
    					"/@([\p{L}]+)/");
    	$replace = array("$1",
    					 "#$1",
    					 "@$1");
    	return preg_replace($search, $replace, $text);
    }
    ?>

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Loading Static Templates for Intern Testing

    I use Intern by SitePen for all of my JavaScript functional testing.  Intern has loads of features other functional test frameworks don't and it's completely Promise-based -- something I got very used to when I used the Dojo Toolkit every day. Async test creation can...

  • Convert Video to mp3

    Let's all be honest for a moment:  we've all ... not paid for ... music.  Whether it was via a file sharing app like Kazaa or Napster, or it was downloading and seeding on bittorrent, or maybe even downloading a music video and ripping its audio,...

  • Sort git Branches by Date

    I'll be first person to admit I don't do as much git repository maintenance as I should.  I rarely delete branches which have been merged, so a git branch execution shows me a mile-long list of branches that likely aren't relevant.  The best way to find branches I've recently...

  • Best Tools and Resources for Web Professionals in 2015

    Looking for the right resources to help you satisfy the needs of your clients? On the lookout for the best tools to help you increase your revenue? Searching for the right software to help you improve your business? Well, then you’ve come to the right place....

  • JavaScript Polling

    Polling with JavaScript is one of those ugly but important functions within advanced front-end user experience and testing practices.  Sometimes there isn't the event you can hook into to signify that a given task is complete, so you need to get your hands dirty and simply poll for...