Home > Article > Backend Development > Weibo short link algorithm PHP version_PHP tutorial
Idea:
1) Generate a 32-bit signature string from the long URL md5, divided into 4 segments, each segment is 8 bytes;
2) For these four segments of loop processing, take 8 bytes, treat them as hexadecimal strings and operate with 0x3fffffff (30 bits 1), that is, ignore processing exceeding 30 bits;
3) These 30 digits are divided into 6 segments. Each 5-digit number is used as an index of the alphabet to obtain a specific character, and the 6-digit string is obtained in sequence;
4) The total md5 string can obtain four 6-digit strings; any one of them can be used as the short URL address of this long URL;
Below is the PHPcode:
function shorturl($url='', $prefix='', $suffix='') {
$base32 = 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 .= $base32[$val];
$int = $int >> 5;
}
$output[] = $out;
}
return $output;
}
$urls = shorturl('http://www.php100.com');
var_dump($urls);