PHP Function To Convert Link in Twitter Status to Url, plus @ and #

I was working on this PHP Twitter application and wanted to convert link in the status to URL, also convert @username to a follow link, and #tag to a search query. So I made this function below: twitterStatusUrlConverter. You can also download it here: http://snipplr.com/view/13136/

/**
*
* twitterStatusUrlConverter
*
* To convert links on a twitter status to a clickable url. Also convert @ to follow link, and # to search
*
* @author: Mardix – https://mardix.wordpress.com, http://www.givemebeats.net
* @date: March 16 2009
* @license: LGPL (I don’t care, it’s free lol)
*
* @param string : the status
* @param bool : true|false, allow target _blank
* @param int : to truncate a link to max length
* @return String
*
* */
function twitterStatusUrlConverter($status,$targetBlank=true,$linkMaxLen=250){

// The target
$target=$targetBlank ? ” target=\”_blank\” ” : “”;

// convert link to url
$status = preg_replace(“/((http:\/\/|https:\/\/)[^ )\r\n]+)/e”, “‘<a href=\”$1\” title=\”$1\”  $target >’. ((strlen(‘$1’)>=$linkMaxLen ? substr(‘$1′,0,$linkMaxLen).’…’:’$1′)).'</a>'”, $status);

// convert @ to follow
$status = preg_replace(“/(@([_a-z0-9\-]+))/i”,”<a href=\”http://twitter.com/$2\” title=\”Follow $2\” $target >$1</a>”,$status);

// convert # to search
$status = preg_replace(“/(#([_a-z0-9\-]+))/i”,”<a href=\”http://search.twitter.com/search?q=%23$2\” title=\”Search $1\” $target >$1</a>”,$status);

// return the status
return $status;
}

Download it here: http://snipplr.com/view/13136/

Use as you please. If you make some updates, I would really appreciate if you send me a copy and share it with others.

Let’s keep coding for the world!

Peace out!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s