how to convert twitter mentions and URLs to active links using regular expressions in php
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) 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 two 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 );
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
SUBSCRIBE TO RSS FEEDS








Leave a Comment