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

WBOY
发布: 2016-07-12 08:54:36
原创
788 人浏览过

微博短链接算法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个字节, 将他看成...
相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!