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

Twitter style bird 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. @stathisg), 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="$1" target="_blank">$1</a>', $tweet );

$tweet = preg_replace('/[#]+([A-Za-z0-9-_]+)/', '<a href="$1" target="_blank">$0</a>', $tweet );

You can find the above wrapped up in a small function, in this GitHub repo.

Image by ~dhuse

there are 5 comments:

  • 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

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

  • Thanks so much for this snippet. Works beautifully.

  • 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

  • @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;