Micro-blog Short link algorithm php version

Source: Internet
Author: User


1) will be a long URL MD5 generated 32-bit signature string, divided into 4 paragraphs, 8 bytes per paragraph;


2 The four-segment loop is processed, and 8 bytes are taken, which he sees as the 16-string and 0X3FFFFFFF ( 30-bit 1) with operations, that is, more than 30 bits of ignored processing;


3) This 30-bit is divided into 6 segments, each 5-digit number takes a specific character as the index of the alphabet, and sequentially obtains a 6-bit string;


4) The total MD5 string can get 4 6-bit strings ; take any one inside to serve as a short URL for this long URL;


The following is PHP code:


Function shorturl ($url = ', $prefix = ', $suffix = ' ' {


$base = Array (


' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ',


' i ', ' j ', ' K ', ' l ', ' m ' , ' n ', ' o ', ' P ',


' Q ', ' R ', ' s ', ' t ', ' u ', ' V ', ' w ', ' X ',


' y ', ' z ', ' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 '); /p>


$hex = MD5 ($prefix. $url. $suffix);


$hexLen = strlen ($hex);


$subHexLen = $hexLen/8;


$output = array ();


for ($i = 0; $i < $subHexLen; $i + +) {


$subHex = substr ($hex, $i * 8, 8);


$int = 0x3fffffff & (1 * (' 0x '. $subHex))


$out = ';


for ($j = 0; $j < 6 $j + +) {


$val = 0x0000001f & $int;/p>


$out. = $base 32[$val];


$int = $int >> 5;


}


$output [] = $out;


}


return $output;


}


$urls = Shorturl (' http://www.php100.com ');


Var_dump ($urls);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.