>  기사  >  백엔드 개발  >  微博短链接算法php版本,微博算法php_PHP教程

微博短链接算法php版本,微博算法php_PHP教程

WBOY
WBOY원래의
2016-07-12 08:54:36792검색

微博短链接算法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>
复制代码

 

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1119774.htmlTechArticle微博短链接算法php版本,微博算法php 思路: 1)将长网址md5生成32位签名串,分为4段, 每段8个字节; 2)对这四段循环处理, 取8个字节, 将他看成...
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.