Last Updated: February 25, 2016
·
1.902K
· iamjeff75

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;
}

5 Responses
Add your response

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 ·