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:

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

Image by ~dhuse

  • web design

    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

  • Stathis

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

  • Adrian

    Thanks so much for this snippet. Works beautifully.

  • Richard

    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

  • Stathis

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