Sep
13
2008
0

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

Written by Kevin in: PHP

Powered by WordPress | Aeros Theme | TheBuckmaker.com WordPress Themes