Convert links, username mentions, and hashtags in a tweet
function twitterify($ret) {
$ret = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1<a href=\"\\2\" target=\"_blank\">\\2", $ret);
$ret = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2", $ret);
$ret = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $ret);
$ret = preg_replace("/#(\w+)/", "<a href=\"http://twitter.com/search?q=\\1\" target=\"_blank\">#\\1</a>", $ret);
return $ret;
}
Written by jean-françois lefebvre
Related protips
5 Responses
Not working with hyperlinks, because you don't close the <a></a> tags in your first two preg_replace calls
function twitterify($ret) {
$ret = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $ret);
$ret = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $ret);
$ret = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $ret);
$ret = preg_replace("/#(\w+)/", "<a href=\"http://twitter.com/search?q=\\1\" target=\"_blank\">#\\1</a>", $ret);
return $ret;
}
over 1 year ago
·
Cleaner version :)
function parseTweet(text) {
var patterns = {
link: /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,
user: /(^|\s)@(\w+)/g,
hash: /(^|\s)#(\w+)/g
};
return text
.replace(patterns.link,'<a href="$1" target="_blank">$1</a>')
.replace(patterns.user, '$1@<a href="http://www.twitter.com/$2" target="_blank">$2</a>')
.replace(patterns.hash, '$1#<a href="http://search.twitter.com/search?q=%23$2" target="_blank">$2</a>');
}
over 1 year ago
·
Twitter: We need to convert the Direct Message and/ or mentions of our followers in a tweet automatically, no way to do
over 1 year ago
·
Thanks for your comment, I fixed this in my code on my mac a long time ago, and I had forgotten to fix the snippet on coderwall. :)
over 1 year ago
·
You are a BOSS, thanks for the code.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#