Shortening Long URLs With PHP

13th June 2008 - 1 minute read time

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 = "!+code&btnG=Search&meta=";
$shorturl = shortenurl($longurl);
echo '<a href="'.$longurl.'" title="'.$longurl.'">'.$shorturl.'</a>';

This will print out the URL string as.[...]nG=Search&amp;meta=



Add new comment

The content of this field is kept private and will not be shown publicly.