代码之家  ›  专栏  ›  技术社区  ›  halocursed

是否为输入字符串/url创建唯一的字母数字字符串?

php
  •  0
  • halocursed  · 技术社区  · 16 年前

    我想为输入字符串创建一个小于或等于10个字符的唯一字符串,该字符串可以是url

    http://stackoverflow.com/questions/ask
    

    programming124
    

    但是结果对于每个输入都应该是唯一的…它们是您在php中用于项目的任何函数或类。。。谢谢

    2 回复  |  直到 16 年前
        1
  •  2
  •   Gumbo    16 年前

    如果需要唯一的随机字符串,可以使用以下函数创建随机字符串:

    function randString($length) {
        $charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        $str = '';
        while ($length-- > 0) {
            $str .= $charset[rand() % 62];
        }
        return $str;
    }
    

    do {
        $randString = randString(10);
        // look up your database if $randString already exists and store the result in $exists
    } while ($exists);
    // store new random string in database
    
        2
  •  0
  •   Kevin Peno    16 年前

    php中最简单的函数是 uniqid . 您提到的时间稍微长了一点,负载平衡不能很好地工作,但是如果您正在做一些非常简单的事情,它应该可以正常工作。

    推荐文章