how to convert twitter mentions, hashtags 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. @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:
1 2 3 4 5 |
$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">$1</a>', $tweet ); $tweet = preg_replace('/[#]+([A-Za-z0-9-_]+)/', '<a href="http://twitter.com/search?q=%23$1" target="_blank">$0</a>', $tweet ); |
You can find the above wrapped up in a small function, in this GitHub repo.
Image by ~dhuse