4

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!

2
  • Its the text inside the <a> tag that gets shortened, not the URL so you may want to re-phrase your question. You can use simple string manipulation for this purpose. Commented Oct 19, 2010 at 8:54
  • There is no <a> anywhere, its just http://www.noupe.com/how-tos/10-ways-to-automatically-manually-backup-mysql-database.html URL and we need to shorten it. and then we'll put it like <a href="long URL">Dynamically generated Short URL</a> Commented Oct 19, 2010 at 9:11

5 Answers 5

7

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>
Sign up to request clarification or add additional context in comments.

2 Comments

While that is true you fail to address the fact that the URI must also be found in the user's input.
I don't think the source for the URLs is that relevant to the question.
2

My guess would be that you just have to search for <a> tags in your source output, and change it's value accordingly. href stays the same, but you change the link name to what you want.

But that's just one idea... You can always experiment with new stuff.

There should also be a way to accomplish this with javascript on-the-go.

Think out of the box!

Comments

1

Here is a function to replace URLs with links. You will just need to adjust how you want to format it. Maybe use parse_url()

<?php
function URLref($sentence){
  $temp = explode(" ", $sentence);
  $new = "";
  foreach($temp as $i){
    if(preg_match('([A-Za-z][A-Za-z0-9+.-]{1,120}:[A-Za-z0-9/](([A-Za-z0-9$_.+!*,;/?:@&~=-])|%[A-Fa-f0-9]{2}){1,333}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*,;/?:@&~=%-]{0,1000}))?)', $i)){
      $new .= '<a href="'.$i.'">'.$i.'</a>';
    }else{
      $new .= "$i ";
    }
  }
  return trim($new);
}
$sentence = "My site ULR is http://www.google.com/lolz.html";

echo URLref($sentence);

2 Comments

Hi i liked your answer , What if we want to shorten the url like the OP said. what if when you echo $sentence it will give My site ULR is http://www.google.com/... ? how to do that ?
dear @petah i guess i fixed it , i have one question , how if the url doesnt have http ? it have only www.google.com how could you modify your regex to find also those url without http:// , thanks
1

You could retrieve URLs using regular expressions, here two examples on how to create <a> tags from found URLs and on how to shorten content of <a> tags:

<?php

$orig_text = <<<TEXT
This is some text. http://www.example.com/this-is-a-quite-long-url-to-be-shortened.html
http://www.example.com/another-url-to-be-shortened and http://www.example.com/another-one-that-is-longer-than-limit then
http://www.example.com/an-ok-url and some text to finish the sentence.

Now, try with an HTTPS url: https://www.example.com/this-https-url-is-too-long.

And with an already-created tag <a href='http://www2.example.com/this-is-another-long-url.html'>http://www2.example.com/this-is-another-long-url.html</a> <a href='http://www2.example.com/my-test-url-goes-here.html'>And this is just some long long link description to be shortened</a>. More text here.

TEXT;

$PATTERN_URL='#(?:href=[\'"]?)?!(https?://([^/]+)/([^\s]+))\b#';
define('URL_LENGTH_LIMIT', 36);

function create_a_tag($matches) {
  $url = $matches[1];
  $label = $matches[1];
  if (strlen($label) > URL_LENGTH_LIMIT) $label = $matches[2] . '/...';
  return "<a href='$url'>$label</a>";
}

function shorten_url_or_text($url) {
  if (strlen($url) > URL_LENGTH_LIMIT) {
    $matches = array();
    if (preg_match('#^(https?://[^/]*).*#', $url, $matches)) {
      // Shorten as for URLS
      return $matches[1] . '/...';
    }
    else {
      // Trim to a given length
      return substr($url, 0, URL_LENGTH_LIMIT-3) . '...';
    }
  }
  else {
    return $url;
  }
}

function shorten_a_text($matches) {
  $text = shorten_url_or_text($matches[2]);
  return $matches[1] . $text . $matches[3];
}

// This will replace urls with their shortened form
echo "----- CREATE <A> TAGS -----\n";
$text2 = preg_replace_callback($PATTERN_URL, 'create_a_tag', $orig_text);
echo $text2 . "\n";

// This will shorten content inside <a> tags
echo "----- CREATE <A> TAGS -----\n";
$text3 = preg_replace_callback('@(<a[^>]*>)([^<]*)(</a>)@i', 'shorten_a_text', $text2);
echo $text3;
echo "\n";

1 Comment

Looks like stackoverflow didn't guess the right syntax highlighter.. and the heredoc string didn't get coloured properly.
-3

To create "custom" URL's that do not have a matching file, you'll have to configure your webserver. If you're using Apache and have the rights to do so, you can take a look at mod_rewrite: http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html

And a tutorial: http://articles.sitepoint.com/article/guide-url-rewriting

2 Comments

The reason that your answer is not correct is that the text displayed in an anchor tag does not have to match the URI pointed to by the anchor tag's href attribute. That said, you are correct that almost all the other URI's on stackoverflow.com are most certainly created using url-rewriting techniques such as those described in the links you have posted.
I simply made a false assumption, when Alin posted his comment I re-read and understood what happened. Thanks for taking the time to explain why you downvoted, though :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.