Micro-blog Short link algorithm php version

Source: Internet
Author: User
Tags array md5 php code

idea:

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

2 to the four-segment loop, take 8 bytes, consider him as 16-string and 0X3FFFFFFF (30-bit 1) and operation, that is, more than 30-bit ignore processing;

3 The 30 bits are divided into 6 segments, each 5 digit number is taken as the index of the alphabet to obtain the specific characters, and then the 6-bit string is obtained.

4) The total MD5 string can obtain 4 6-bit strings; Taking any one inside can be used as the short URL of this long URL;

Here is the 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 ');

$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 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.