Hot Koehls

The more you know, the more you don’t know

This content is a little crusty, having been with me through 3 separate platform changes. Formatting may be rough, and I am slightly less stupid today than when I wrote it.
15 Dec 2008

Parse URL's in text, create links

I’m absolutely in love with the status update stream I’ve put together for Fwd:Vault (follow link for example). However in the process, I’ve discovered a huge drawback to the Twitter messaging system: it does not store links. The Twitter site itself will identify URL’s in messages and convert them into clickable links for you automatically. But the magic ends at Twitter’s borders; anyone who wants to do the same on their site is on their own. So I consulted the almighty Google. I found plenty of raw regex, javascript, and Twitter-focused discussions on the matter, but I found the offered solutions and tips lacking. I wanted to do this up right, transparently via PHP in the background. No JS required. Finally, I found a small PHP script that accomplished what I needed. Here’s a renamed version—all code intact—that will find and convert any well-formed URL into a clickable <a> tag link. Update: My buddy Tonk has updated the code to link up @replies and #hashtags as well. He also switched from POSIX to Perl regular expressions syntax, mostly cause he’s a regex dork.

function linkify( $text ) {

  $text = preg_replace( '/(?!<\S)(\w+:\/\/[^<>\s]+\w)(?!\S)/i', '$1', $text );

  $text = preg_replace( '/(?!<\S)#(\w+\w)(?!\S)/i', '#$1', $text );

  $text = preg_replace( '/(?!<\S)@(\w+\w)(?!\S)/i', '@$1', $text );

  return $text;

}

```

Copy that into your code, then run your text containing unlinked URL's through it. Let's apply it to the Twitter feed example as we left it in Step 2:
* text) . '
' . $time_display; ?>

```

You can find this code at work on Fwd:Vault.
**Build a slick Twitter feed on your site**
    * Display Twitter updates on your website * Calculate dates and times in different timezones (translate Twitter timestamps)
  1. Parse URL’s in text, create links

comments powered by Disqus