开发者

how to generate shortest possible string in php? [duplicate]

This question already has answers here: 开发者_如何学C Closed 12 years ago.

Possible Duplicate:

How to code a URL shortener?

How to generate shortest possible string (the way e.g. bit.ly is doing this)?


Well you would have to make random string and then check if you allredy have it in your database! Here i write you a example how to. Btw. this is just a quick one. There are much more things that could be checked to speed it up!

$cl=2;
$cr=0;
$n="";
while(!$e){
  if($cr>500){$cr=0;$cl++;}
  $n=genRandomString($cl);
  $checker = mysql_query("select count(*) as haveit from table where thestring='".$n."'");
  $xa = mysql_fetch_array($checker);
  if($xa['haveit']==0){$e=1;}
  $cr++;
}

function genRandomString($len){
    $length = $len;
    $characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $string = '';
    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }
    return $string;
}

This is just to give you idea how to do it! This have to be optimized a little! :D

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜