Ideas:
1) to generate a long URL MD5 32-bit signature string, divided into 4 segments, 8 bytes per segment;
2) for this four-segment cycle processing, take 8 bytes, he is regarded as 16 binary string and 0X3FFFFFFF (30 bit 1) and operation, that is, more than 30 bits of ignoring processing;
3) The 30 bits are divided into 6 segments, and each 5 digit number is taken as an index of the alphabet to obtain a specific character, followed by a 6-bit string;
4) The total MD5 string can obtain 4 6-bit strings; Take any one inside to be the short URL address for this long URL;
Here is the PHP code:
functionShorturl ($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 '); $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; $out.=$base[$val]; $int=$int>> 5; } $output[] =$out; } return $output;} $urls= Shorturl (' http://www.dareng.com ');Var_dump($urls);
Results:
Array (4) { [0]=> string(6) "alms1l" [1]=> string(6) "2ipmby" [2]=> string(6) "Avo1hu" [3]=> string (6) "Fdlban"}
Weibo short link algorithm PHP version