Tag Archives: tinyurl

Script to shorten the long urls present in your status or text

I described in my last two posts http://tinyurl.com/62pf6td and  http://tinyurl.com/5tpd9rk how to identify a  url in some text and how to make tiny url api calls. In this post, I describe how I proceeded on to make a simple script in which I could provide as input some text which may contain several urls and then execute the script to identify the urls present and replace them by tinyurls using tinyurl.com api calls.

First, I created a html form to take input text.

<form method="post" action="status.php">
 <p> Status: <br />
 <textarea rows=4 cols=90 name="status" value="">
 </textarea>
 </p>    
 <p> <input type="submit" value="Shorten urls"/> </p>
 </form>

Then, I wrote a function for making the api call to tinyurl.com and replacing the urls .

function tweet_status($status){
 $result = $status;
 $pattern = "(((https?)\:\/\/)|(www\.))";
 $pattern .= "[A-Za-z0-9][A-Za-z0-9.-]+(:\d+)?(\/[^ ]*)?";

 if(!empty($status)){
 if (preg_match_all("/$pattern/",$status,$matches)){
 foreach($matches[0] as $url){
 $short_url = shortURL($url);
 $result = str_replace($url,$short_url,$result);
 }
 }  
 }
 return $result;
}

The code for making the above function call after reading the text from text area element in form is:

$status = trim($status);
$short_status = tweet_status($status);
if(!empty($status)){
 $length = strlen($short_status);
 /* This function call may be skipped as url gets hyperlinked
 by itself when copied to twitter status field */
 $short_status = hyperlink($short_status);
 echo "<p>Shortened status:<br /> $short_status</p>";        
 echo "<p>Characters now: $length</p>";
}

You may have observed there is a call to function hyperlink(). This function call is used to add the hyperlink tag to the url. The code for it is as follows:

function hyperlink($status){
 $pattern = "(((https?)\:\/\/)|(www\.))";
 $pattern .= "[A-Za-z0-9][A-Za-z0-9.-]+(:\d+)?(\/[^ ]*)?";

 if(!empty($status)){
 if (preg_match_all("/$pattern/",$status,$matches)){
 foreach($matches[0] as $url){
 $hyperlink_url = "<a href=\"$url\">$url</a>";
 $status = str_replace($url,$hyperlink_url,$status);
 }
 }
 }
 return $status;
}

You can try out using this simple script present at http://tinyurl.com/4zpvrg7 . You may have noticed that all the urls mentioned in this post are of the form tinyurl.com. All these urls have been obtained by using this script.

This script can be used to update a status containing a few urls, without the user bothering to convert the long urls individually by using a url shortener web service. I shall add a "Tweet button" to this script soon so that the shortened status can be tweeted and hence eliminating the need of user using this script to copy the output text and then paste it in twitter.com.