PHP: Autolink Text – Twitter @replies

Update: To prevent any confusion the code highlighter might cause in the post, I added a plain text version of this post here.
I noticed a lot of sites allow user submitted content but prevent autolinking of urls. Some of the most common instances of this are on Twitter sites (much like my own creation: SecretTweet.com). So I threw together a function to autolink urls:

 
<?
$text= 'Hey go to google.com moo http://google.com moo www.google.com moo http://wwww.google.com/404.php moo';
function linkify(&$text)
{
//CONVERT *://.* TO LINK (EG HTTP://KEVINSMITHDESIGNS.COM)
$text = ereg_replace("[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*", "\\0", $text);
//CONVERT *://*.* TO LINK (EG HTTP://WWW.KEVINSMITHDESIGNS.COM)
$text = ereg_replace("(^| )(www([.]?[a-zA-Z0-9_/-])*)", "\\1\\2", $text);
return $text;
}
echo linkify($text);
?>
 

Would return "Hey go to google.com moo http://google.com moo www.google.com moo http://wwww.google.com/404.php moo".

And since I made this primarily for Twitter, the following will linke @ replies automatically, too:

 
<?
$tweet = "Hey @mozunk! Go check out http://digsby.com -- I think you will like it.";
function twitterify(&$tweet) {
//CONVERT *://.* TO LINK (EG HTTP://KEVINSMITHDESIGNS.COM)
$tweet = ereg_replace("[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*", "\\0", $tweet);
//CONVERT *://*.* TO LINK (EG HTTP://WWW.KEVINSMITHDESIGNS.COM)
$tweet = ereg_replace("(^| )(www([.]?[a-zA-Z0-9_/-])*)", "\\1\\2", $tweet);
//LINK @USERNAME
$tweet = preg_replace('/([\.|\,|\:|¡|¿|\>|\{|\(]?)@{1}(\w*)([\.|\,|\:|\!|\?|\>|\}|\)]?)\s/i', "$1@$2$3 ", $tweet);return $tweet;
}
echo twitterify(&$tweet);
?>
 

Would return "Hey @mozunk! Go check out http://digsby.com -- I think you will like it."

I'll be implementing this into SecretTweet pretty soon. I haven't decided if I want to autolink URLs or not...maybe just @replies.
---
automatically link urls php
autolink @ replies Twitter automatically link php

2 Comments

  1. 5:13 pm - February 9th, 2009

    Rob says:

    Kevin,

    I found your code via Google and I am very interested in using the function to make @replies into links. However neither of them are working on my server. Are there some special requirements? I am currently using Linux with Apache 1.3.41 and PHP 5.2.6.

    When I use this code, no links are generated. I did make sure to use the version in your plain text file, instead of the syntax highlighted version. Could you maybe verify that this is working corrently?

    Thanks!

  2. 4:57 am - February 16th, 2009

    Rob says:

    Kevin,

    If you have a look at the linked forum post above, you can see the code that I used (submitted by MarkRH) to get this working for me.

    Thanks

1 Trackback

  1. 5:13 pm - February 9th, 2009

    [...] Kevin Smith PHP: Autolink Text – Twitter replies This was the one that I found. But it doesn’t work. __________________ fury

Leave a Comment

(required)
(will not be published) (required)