首頁 > php教程 > php手册 > 主體

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

WBOY
發布: 2016-06-13 08:42:04
原創
949 人瀏覽過

微博短链接算法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>
登入後複製

 

 

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門推薦
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!