Snipe.Net Geeky, sweary things.

PHP Regex to Make Twitter Links Clickable

P

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
[sourcecode language=’php’]function twitterify($ret) {
$ret = preg_replace(“#(^|[\n ])([\w]+?://[\w]+[^ \”\n\r\t< ]*)#", "\\1\\2″, $ret);
$ret = preg_replace(“#(^|[\n ])((www|ftp)\.[^ \”\t\n\r< ]*)#", "\\1
\\2″, $ret);
$ret = preg_replace(“/@(\w+)/”, “
@\\1“, $ret);
$ret = preg_replace(“/#(\w+)/”, “#\\1“, $ret);
return $ret;
}[/sourcecode]

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.

About the author

snipe

I'm a tech nerd from NY/CA now living in Lisbon, Portugal. I run Grokability, Inc, and run several open source projects, including Snipe-IT Asset Management. Tweet at me @snipeyhead, skeet me at @snipe.lol, or read more...

By snipe
Snipe.Net Geeky, sweary things.

About Me

I'm a tech nerd from NY/CA now living in Lisbon, Portugal. I run Grokability, Inc, and run several open source projects, including Snipe-IT Asset Management. Tweet at me @snipeyhead, skeet me at @snipe.lol, or read more...

Get in Touch