且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Zend Framework 生成唯一字符串

更新时间:2023-02-19 23:41:33

使用给定的信息:

  • id 必须是唯一的
  • id 不能是数字
  • id 不能代表一个连续的系列
  • 用户不会输入id

PHP 函数 uniqid 正是您所需要的.虽然它返回一个 13 个字符长的十六进制值.

The PHP function uniqid is exactly what you need. Though it returns a 13 character long hexadecimal value.

** 编辑 **

是的,uniqid 会返回一个连续的数字,但我们可以轻松解决这个问题.考虑这个代码

Yes, uniqid will return a seamingly sequential number, but we can get around this easily. Consider this code

class IDGenerator {
   //const BIT_MASK = '01110011';

   static public function generate() {

      $id = uniqid();

      $id = base_convert($id, 16, 2);
      $id = str_pad($id, strlen($id) + (8 - (strlen($id) % 8)), '0', STR_PAD_LEFT);

      $chunks = str_split($id, 8);
      //$mask = (int) base_convert(IDGenerator::BIT_MASK, 2, 10);

      $id = array();
      foreach ($chunks as $key => $chunk) {
         //$chunk = str_pad(base_convert(base_convert($chunk, 2, 10) ^ $mask, 10, 2), 8, '0', STR_PAD_LEFT);
         if ($key & 1) {  // odd
            array_unshift($id, $chunk);
         } else {         // even
            array_push($id, $chunk);
         }
      }

      return base_convert(implode($id), 2, 36);
   }
}

echo IDGenerator::generate();

哪个会给出类似的结果

ivpa493xrx7
d173barerui
evpoiyjdryd
99ej19mnau2

由于没有添加或修改任何内容,除了改组周围的位,不应该有任何重复的值,一切似乎都是随机的.瞧!

Since there is nothing added or modified, except shuffling the bits around, there should not be any duplicated values and everything seems random. Voilà!

自从它最初发布以来,我就更新了这段代码.您可能会找到修订版 这里

I update this piece of code since the time it was originally posted. You may find the revised version here