Friday, 10 August 2018

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.
  1. function shortenurl($url)
  2. {
  3. if ( strlen($url) > 45) {
  4. return substr($url, 0, 30)."[...]".substr($url, -15);
  5. } else {
  6. return $url;
  7. }
  8. }
You can use the function in the following way.
  1. // long URL, in this case a Google search query
  2. $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=";
  3. $shorturl = shortenurl($longurl);
  4. echo '<a href="'.$longurl.'" title="'.$longurl.'">'.$shorturl.'</a>';
This will print out the URL string as.
http://www.google.co.uk/search[...]nG=Search&meta=

0 comments:

Post a Comment