Snipe.Net - Geeky Stuff

PHP Regex to Make Twitter Links Clickable

This is just a quicky post, not one of my usual long, rambling diatribes. This week is madness, even by my own absurd standards, but I didn’t want to miss jotting this down in case it might be helpful to others.

I’ve had varying degrees of success trying to find a series of preg_replace statements that would correctly replace output generated by Twitter’s RSS feeds (which do not contain any linking HTML) to autolink hyperlinks, @replies and hashtags, so I finally sat down and sorted it out myself.

The code below should correctly autolink all of the autolinkables in your PHP script:

  • links @username to the user’s Twitter profile page
  • links regular links to wherever they should link to
  • links hashtags to a Twitter search on that hashtag
function twitterify($ret) {
  $ret = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $ret);
  $ret = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $ret);
  $ret = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $ret);
  $ret = preg_replace("/#(\w+)/", "<a href=\"http://search.twitter.com/search?q=\\1\" target=\"_blank\">#\\1</a>", $ret);
return $ret;
}

Someday I’ll try to find the time to write a regex primer/tutorial. Regex is another one of the things, like SVN, that seems scary and incomprehensible to many people, but eventually it clicks and makes sense. In the meantime, if you’re interested in learning more about using Regex in PHP, check out the following resources:

More Regexy Goodness:

Make sure you leave yourself some time to actually try out some examples, and dissect the examples they give so that you really grok what’s happening. Once it clicks, it seems so simple, you won’t believe you ever let it beat you up and take your lunch money.

Image by xkcd, via their awesome web store. The comic rocks my geeky face off. I buy my clothes there. So should you.

PS – still really, really hate posting code in WordPress. Even in HTML mode, it keeps converting my fscking special characters, which then get double/triple/etc converted.

Also check out:

If you think this article kicked ass, subscribe to the RSS feed or follow me on Twitter! Share with your friends, or leave a comment below (or better still, do both!) My entire concept of self-worth is in your hands, so that makes you kind of a big deal. Srsly.

This entry was posted on Thursday, September 10th, 2009 at 4:44 am and is filed under PHP/mySQL, Web Development. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

View Comments to “PHP Regex to Make Twitter Links Clickable”

  1. Sep 11th

    this is awesome, i made one modification – your first two replacements forgot to close the link.
    .-= mike´s last blog ..the family at home =-.

  2. Sep 11th

    I’ll be damned, you’re right… lol – how the hell did I do that? Thanks for the heads up – I’ll fix it.

  3. Sep 14th

    Okay – weirdly, I didn’t forget the closing anchor tags – WordPress keeps stripping them out, no matter how many times I re-add them. WTF?

  4. Sep 19th

    Not if this matters but I was getting “bad escape” warnings from Zend Studio. You can see the changes I made below.

    $string = preg_replace(“#(^|[\n ])([\\w]+?://[\\w]+[^ \"\n\r\t< ]*)#", "\\1\\2“, $string);
    $string = preg_replace(“#(^|[\n ])((www|ftp)\\.[^ \"\t\n\r< ]*)#", "\\1\\2“, $string);
    $string = preg_replace(“/@(\\w+)/”, “@\\1“, $string);
    $string = preg_replace(“/#(\\w+)/”, “#\\1“, $string);

  5. That’s a great one, I really was thinking about using regex to make links clickable, but here you are =]
    can’t live without your code ;) haha

  6. Oct 8th

    Wait, I caught a bug.
    If you parse a message like this “blah..blah..blah http://www.google.com?“,
    the question mark will be included in the url.

  7. Oct 22nd

    Thanks a lot for this nice function!

  8. Nov 8th

    That's very cool tips. Thanks for your post.

  9. Bill K
    Nov 12th

    Awesome! Thank you so much. I've been trying for a week to do this and being new to Regex was getting strange results (if any).

  10. Nov 16th

    You can't use this on HTML code without risking to destroy your HTML. Example:

    Don't break!

    (… let's hope this thing doesn't post my link as link but as HTML code ;) )

  11. Nov 16th

    Twitter doesn't allow HTML code, so that's not really an issue.

  12. Ninja Developer
    Nov 20th

    Thanks buddy, that made my day :)

  13. amidar
    Nov 21st

    So how do you apply this function in a tweet or rss?
    Sorry to sound dumb but would appreciate an example

  14. Nov 21st

    You wouldn't use it in a tweet or RSS, you would use it in a PHP script that parses tweets or tweet RSS feeds.

    echo twitterify($tweet_content);

  15. Nov 23rd

    Please let me know how to implement this on my twitter. Thank you

  16. Nov 23rd

    You don't implement it on your Twitter – Twitter already does auto-linking for you. You would use this in an application or web page that is pulling directly from your Twitter feed and emebdding in the page.

  17. Dec 14th

    This is beautiful.. no seriously, almost made me cry when I saw it. I was about to put “twitter-ifying” my twitter RSS feed on the back-burner, but this is drop-in beauty. Thanks.

  18. Dec 31st

    LOL It's good to know you're not prone to hyperbole or anything. :D I'm glad it helped!

  19. Jan 1st

    LOL It's good to know you're not prone to hyperbole or anything. :D I'm glad it helped!

  20. Joel R
    Jan 8th

    This totally kicks ass and saved me a good hour+ of work and I'm really good with regexs.

    Thanks!!

  21. Jan 8th

    Excellent – glad to hear it!

  22. Stace
    Feb 5th

    This is great! I'm just learning preg replace and regex and had already spent some time trying to figure this out with no result in sight. Thank you very much.

    One quickie, though: email addresses. Some tweets contain 'you@gmail.com' with the predictable result of only '@gmail' linking to http://www.twitter.com/gmail. Any thoughts on a fix?

    Thanks again!

  23. Feb 17th

    Very nice. I remember when Regex seemed like magic, but now it is one of my most often used tools.

  24. Feb 17th

    I think that's the exact same set of regular expressions I'm using to parse links on my website home page.

  25. Mar 4th

    I use this on Media UK – http://www.mediauk.com – to power a few things, including the ingest of the media tweets on the front page.

    You might like to add
    $ret = html_entity_decode($ret);
    at the start of the function – otherwise you see odd things going on when Twitter (or some client) HTML-encodes things like pound signs.

  26. Mar 19th

    This is awesome, thanks! I started to write my own with a bunch of if's, else's and substr_replace(), and substr() but it quickly became a mess. I really need to learn regex!

  27. Mar 19th

    Hehe – yeah, regex rocks, but it can be a little confusing. There are some great tutorials online though. Stick with it!

  28. Luboš
    Mar 29th

    Thanks a lot!!! There is problem with some characters in parsed text. For exapmle #Nestlé is not parsed right

  29. Mar 29th

    It looks like Twitter doesn't really acknowledge the character, and just converts it to a regular, unaccented 'e': https://twitter.com/#search?q=%23Nestl%C3%A9

  30. evilunix
    Apr 13th

    I converted this function to javascript :)

    function twitterify(ret) {

    ret = ret.replace(/(^|[n ])([w]+?://[w]+[^ "nrt< ]*)/, “$1$2“);
    ret = ret.replace(/(^|[n ])((www|ftp).[^ "tnr< ]*)/, “$1$2“);
    ret = ret.replace(/@(w+)/, “@$1“);
    ret = ret.replace(/#(w+)/, “#$1“);

    return ret;

    }

  31. Apr 13th

    Nice work, thanks!

  32. evilunix
    Apr 13th

    The HTML tags seem to have gone missing from the replace parts of those statements! Anyway, the basic idea is to replace \1 with $1. The hash delimiters should be replaced with forward slashes, which means any other forward slashes need escaping with backslashes!

  33. Bop
    Apr 16th

    Just excellent!

  34. Apr 19th

    Nice function.But, I need some help.
    The URL “http://test.com/test.htm#test”does'nt links correctly. Twitter parsed this as complete url (no hastag). Your function parsed a hastag, wich is not correct.

    Can you fix this?

  35. Apr 19th

    I have modified your function. This code fixes the bug i wrote in my last comment.
    It fix also the “you@gmail.com”-bug. I hope it is helpfully!

    function twitterify($ret) {
    $ret = preg_replace(“#(^|[n ])([w]+?://[w]+[^ "nrt< ]*)#”, “\1\2“, $ret);
    $ret = preg_replace(“#(^|[n ])((www|ftp).[^ "tnr< ]*)#”, “\1\2“, $ret);
    $ret = preg_replace(“/(^| )@(w+)/”, “@\1“, $ret);
    $ret = preg_replace(“/(^| )#(w+)/”, “\1#\2“, $ret);
    return $ret;
    }

  36. Apr 20th

    Damn! There was an mistake in my posted code, sorry!
    This code should be work:

    function twitterify($ret) {
    $ret = preg_replace(“#(^|[n ])([w]+?://[w]+[^ "nrt< ]*)#”, “\1\2“, $ret);
    $ret = preg_replace(“#(^|[n ])((www|ftp).[^ "tnr< ]*)#”, “\1\2“, $ret);
    $ret = preg_replace(“/(^| )@(w+)/”, “\1@\2“, $ret);
    $ret = preg_replace(“/(^| )#(w+)/”, “\1#\2“, $ret);
    return $ret;
    }

  37. Ecenica
    Jul 2nd

    Thanks for sharing this snippet of code! Now using it with SimplePie and Smarty to bring our Twitter into our customer hosting panel.

  38. VanishDesign
    Jul 16th

    This is really cool, but it looks like a 'smart' apostrophe (’)will break it

  39. I want you to know that i LOVE you! Finally I found something that works!!!

  40. Jul 20th

    Yes, of course. Smart quotes are not recognized as quote marks.

  41. Deratrius
    Aug 24th

    Nice work, noticed that if there is a regular link between parentheses the the link isn’t parsed.
    eg: http://www.link.com is parsed but (www.link.com) isn’t.

Pingbacks

  1. [...] PHP Regex to Make Twitter Links Clickable | Snipe.Net [...]

  2. [...] properly decode the HTML entities. We’ve submitted that small change to the producer of the original code snippet we use to achieve the clever links. (Agree on technology, compete on [...]

  3. [...] you tweet, grab this function by Alison Gianotto to help auto-link those [...]

  4. [...] you tweet, grab this function by Alison Gianotto to help auto-link those [...]

  5. [...] you tweet, grab this function by Alison Gianotto to help auto-link those [...]

  6. [...] shortly after posting I found this post, which provides an excellent little function that finds and creates the links in your tweets using [...]

Leave a Reply

Like this site? Buy me a beer!
blog comments powered by Disqus