Shortening Long URLs With PHP

Print out a full URL for a link will sometimes mess up your formatting, especially if you URL is quite long. This might be the case if you are linking to a Google search page, or have an automated script that shows numerous URLs of indeterminate length. The following function will reduce any URL longer than 45 characters by splitting it in two and join them up with a simple string.

function shortenurl($url)
{
 if ( strlen($url) > 45) {
  return substr($url, 0, 30)."[...]".substr($url, -15);
 } else {
  return $url;
 }
}

You can use the function in the following way.

// long URL, in this case a Google search query
$longurl = "http://www.google.co.uk/search?aq=f&num=100&hl=en&client=firefox-a&channel=s&rls=org.mozilla%3Aen-US%3Aofficial&q=#!+code&btnG=Search&meta=";
$shorturl = shortenurl($longurl);
echo '<a href="'.$longurl.'" title="'.$longurl.'">'.$shorturl.'</a>';

This will print out the URL string as.

http://www.google.co.uk/search[...]nG=Search&amp;meta=

 

Comments

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
9 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.