Finding URL’s and hashtags in tweets and make them hyperlinks using PHP

Best example is to make the links and hashtags in your tweets hyperlinks

Vivek Arora
Simple Web Tutorials
2 min readNov 30, 2013

--

See the working demo here

Recently I used the twitter feed API using PHP to load my latest 5 tweets and noted that the tweets returned were just plain text. This tutorial will explain how to find if the text contains url’s starting with http, https and would convert them to links so they can visited by clicking on them. The best example would be to make the links in the tweet if you are using the twitter API to load the tweets. Here is a simple code snippet used

<?php
//Regular expression filter used to match the links within text.
$regex = “/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/”;

// The Text could be anything, I am using one of my latest tweets.
$tweet = “animated border menus http://t.co/q3CANb19Rw #webdesign #webdev #freebies”;

// check if there is a url in the text
if(preg_match($regex, $tweet, $url)) {

// if the url exists, make them a hyperlink to the specific page
echo preg_replace($regex, “<a href=’”.$url[0].”’ target=’blank’>”.$url[0].”</a> “, $tweet);

}
?>

I just noticed that Medium has converted the http link my example tweet to a link. That is a very good example right there. Now, we are going to make the hashtags present in the tweets hyperlink to the specific location.

//Regular expression filter used to match hashtags in a string.
$regex = ‘/(^|\s)#(\w*[a-zA-Z_]+\w*)/’;

$tweet = “animated border menus http://t.co/q3CANb19Rw #webdesign #webdev #freebies”;

$tweet = preg_replace($regex, ‘\1<a href=”http://twitter.com/search?q=%23\2">#\2</a>’, $tweet);

--

--

Vivek Arora
Simple Web Tutorials

passionate web guy and constant learner. tweets and blogs tutorials on #webdesign #html #css #jquery #php. follow me @vivekarora86 http://vivekarora.com/blog