Home > Article > Backend Development > Weibo short link algorithm php version Weibo link address Weibo send link Weibo send link
Ideas:
1) Generate a 32-bit signature string from md5 of the long URL, divided into 4 segments, each segment is 8 bytes;
2) Process these four segments in a loop and take 8 bytes, Think of it as a hexadecimal string and 0x3fffffff (30 bits 1) and operate, that is, more than 30 bits are ignored;
3) These 30 bits are divided into 6 segments, and each 5-digit number is used as an index of the alphabet to obtain a specific Characters, proceed in sequence to obtain 6-digit strings;
4) The total md5 string can obtain 4 6-digit strings; any one of them can be used as the short url address of this long url;
The following is PHP code:
<span>function</span> shorturl(<span>$url</span>='', <span>$prefix</span>='', <span>$suffix</span>=''<span>) { </span><span>$base32</span> = <span>array</span><span> ( </span>'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'<span>); </span><span>$hex</span> = <span>md5</span>(<span>$prefix</span>.<span>$url</span>.<span>$suffix</span><span>); </span><span>$hexLen</span> = <span>strlen</span>(<span>$hex</span><span>); </span><span>$subHexLen</span> = <span>$hexLen</span> / 8<span>; </span><span>$output</span> = <span>array</span><span>(); </span><span>for</span> (<span>$i</span> = 0; <span>$i</span> $subHexLen; <span>$i</span>++<span>) { </span><span>$subHex</span> = <span>substr</span> (<span>$hex</span>, <span>$i</span> * 8, 8<span>); </span><span>$int</span> = 0x3FFFFFFF & (1 * ('0x'.<span>$subHex</span><span>)); </span><span>$out</span> = ''<span>; </span><span>for</span> (<span>$j</span> = 0; <span>$j</span> $j++<span>) { </span><span>$val</span> = 0x0000001F & <span>$int</span><span>; </span><span>$out</span> .= <span>$base32</span>[<span>$val</span><span>]; </span><span>$int</span> = <span>$int</span> >> 5<span>; } </span><span>$output</span>[] = <span>$out</span><span>; } </span><span>return</span><span>$output</span><span>; } </span><span>$urls</span> = shorturl('http://www.dareng.com'<span>); </span><span>var_dump</span>(<span>$urls</span>);
Result:
<span>array</span>(4<span>) { [</span>0]=> <span>string</span>(6) "alms1l"<span> [</span>1]=> <span>string</span>(6) "2ipmby"<span> [</span>2]=> <span>string</span>(6) "avo1hu"<span> [</span>3]=> <span>string</span>(6) "fdlban"<span>}</span>
The above introduces the PHP version of the Weibo short link algorithm, including the content of Weibo short links. I hope it will be helpful to friends who are interested in PHP tutorials.