Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorten URL text on links like stackoverflow?

Tags:

url

php

short

I need some help in PHP to create short urls just like StackOverflow creates when we comment any long URL in comments on a question.

StackOverflow shortens http://www.noupe.com/how-tos/10-ways-to-automatically-manually-backup-mysql-database.html long url to short urls like this noupe.com/...

I require similar kind of functionality in my application. Can anyone give some idea or code how to do that in PHP?

I tired searching it on StackOverflow but not found any question. I remember I had seen such type of question on SO, but right now I am not able to find it :(

Please help!

like image 755
djmzfKnm Avatar asked Feb 26 '23 01:02

djmzfKnm


1 Answers

Just an outline of a simplistic algorithm.

  1. See if the link has more than X chars in length.
  2. Remove the http:// or https:// at the beginning with str_replace.
  3. Explode at / and only keep the first item in the returned array.
  4. If you found more than 1 item at step 3 add /... at the end.
  5. Optional. Remove the www. at the begining with str_replace.

With this found string, naming it [shortURL], you compose your anchor:

<a href="[fullURL]">[shortURL]</a>
like image 137
Alin Purcaru Avatar answered Mar 06 '23 21:03

Alin Purcaru