how to convert twitter mentions, hashtags and URLs to active links using regular expressions in php

Twitter style bird by dhuse on deviantART

Creation by ~dhuse on deviantART

If you are using twitter’s API to display your tweets in your Website you have probably faced the problem that your mentions (e.g. @burnmind), hashtags (e.g. #question) and URLs are displayed as plain text and not as active links. You can fix this in a very easy way, using regular expressions in php.

Assuming that you have stored your tweet in the variable named $tweet, you’ll only need the following three lines of code to convert the mentions and URLs to links:

$tweet = preg_replace("/((http)+(s)?:\/\/[^<>\s]+)/i", "<a href=\"\\0\" target=\"_blank\">\\0</a>", $tweet );

$tweet = preg_replace("/[@]+([A-Za-z0-9-_]+)/", "<a href=\"http://twitter.com/\\1\" target=\"_blank\">\\0</a>", $tweet );

$tweet = preg_replace("/[#]+([A-Za-z0-9-_]+)/", "<a href=\"http://twitter.com/search?q=%23\\1\" target=\"_blank\">\\0</a>", $tweet );

If you don’t know how to retrieve your tweet using the twitter’s API you can learn how by reading the following tutorials:

how to retrieve and display your latest tweet using PHP
how to store and retrieve your latest tweet from an XML file

there are 5 comments:

  1. Does this code also account for #hashtags within tweets or are #hashtags not even applicable in this case because the # mark is a type of link internal only to twitter.com?

  2. You can do it easily by altering the second regular expression (I updated the post to include it).

  3. Thanks so much for this snippet. Works beautifully.

  4. What if you want to retrieve retweets? Let’s say joe_soap: RT @Blah_Blah This is a test #tweet ; Using the normal regular expression doesn’t match @Blah_Blah

  5. @Richard: If you store the tweet in the $tweet variable and you pass it through all of the above regular expressions, you’ll get the outcome that you want (the hash-tag as a search link and the username as a profile link).

    Test it yourself:

    $tweet = ‘RT @Blah_Blah This is a test #tweet ‘;
    //include the regular expressions here
    echo $tweet;

Leave a Comment