Short unique id in php

前端 未结 16 995
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 17:34

I want to create a unique id but uniqid() is giving something like \'492607b0ee414\'. What i would like is something similar to what tinyurl gives:

16条回答
  •  时光说笑
    2020-11-29 18:07

    @gen_uuid() by gord.

    preg_replace got some nasty utf-8 problems, which causes the uid somtimes to contain "+" or "/". To get around this, you have to explicitly make the pattern utf-8

    function gen_uuid($len=8) {
    
        $hex = md5("yourSaltHere" . uniqid("", true));
    
        $pack = pack('H*', $hex);
        $tmp =  base64_encode($pack);
    
        $uid = preg_replace("#(*UTF8)[^A-Za-z0-9]#", "", $tmp);
    
        $len = max(4, min(128, $len));
    
        while (strlen($uid) < $len)
            $uid .= gen_uuid(22);
    
        return substr($uid, 0, $len);
    }
    

    Took me quite a while to find that, perhaps it's saves somebody else a headache

提交回复
热议问题