Heim >php教程 >php手册 >微博短链接算法php版本,微博算法php

微博短链接算法php版本,微博算法php

WBOY
WBOYOriginal
2016-06-13 08:42:04963Durchsuche

微博短链接算法php版本,微博算法php

思路:
1)将长网址md5生成32位签名串,分为4段, 每段8个字节;
2)对这四段循环处理, 取8个字节, 将他看成16进制串与0x3fffffff(30位1)与操作, 即超过30位的忽略处理;
3)这30位分成6段, 每5位的数字作为字母表的索引取得特定字符, 依次进行获得6位字符串;
4)总的md5串可以获得4个6位串; 取里面的任意一个就可作为这个长url的短url地址;

下面是PHP代码:

<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> < <span>$subHexLen</span>; <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> < 6; <span>$j</span>++<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>);

结果:

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

 

 

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn