PHP 中的随机 ID/数字生成器 [英] Random ID/Number Generator in PHP

查看:73
本文介绍了PHP 中的随机 ID/数字生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在根据以下要求在我的数据库中构建代理 ID"列表:

I am building a list of "agent id's" in my database with the following requirements:

  1. ID 的长度必须为 9 位(仅限数字)
  2. ID 不能包含超过 3 个相同的数字.
  3. ID 不能连续包含超过 2 个相同的数字(即 887766551;不能有 888..)

到目前为止,我已经完成了第 1 部分,但正在努力解决上面的第 2 部分和第 3 部分.我的代码如下.

So far I have part 1 down solid but am struggling with 2 and 3 above. My code is below.

function createRandomAGTNO() {
    srand ((double) microtime( )*1000000);
    $random_agtno = rand(100000000,900000000);
    return $random_agtno;
}

// Usage
$NEWAGTNO = createRandomAGTNO();

有什么想法吗?

推荐答案

  1. 不要在每次调用时重新设置 RNG,除非您想彻底破坏随机数的安全性.
  2. 除非您的 PHP 很旧,否则您可能根本不需要重新播种 RNG,因为 PHP 在启动时为您播种,并且在极少数情况下您需要用您的一种替换种子自己选择.
  3. 如果您可以使用它,请使用 mt_rand 而不是 rand.我的示例将使用 mt_rand.
  1. Do not re-seed the RNG on every call like that, unless you want to completely blow the security of your random numbers.
  2. Unless your PHP is very old, you probably don't need to re-seed the RNG at all, as PHP seeds it for you on startup and there are very few cases where you need to replace the seed with one of your own choosing.
  3. If it's available to you, use mt_rand instead of rand. My example will use mt_rand.

至于其余部分——您可能会想出一个非常巧妙的将线性范围内的数字映射到您想要的形式的数字的方法,但让我们用蛮力代替它.这是其中之一,是的,运行时间的理论上限是无限的,但预期运行时间是有界的,而且非常小,所以不要太担心.

As for the rest -- you could possibly come up with a very clever mapping of numbers from a linear range onto numbers of the form you want, but let's brute-force it instead. This is one of those things where yes, the theoretical upper bound on running time is infinite, but the expected running time is bounded and quite small, so don't worry too hard.

function createRandomAGTNO() {
  do {
    $agt_no = mt_rand(100000000,900000000);
    $valid = true;
    if (preg_match('/(\d)\1\1/', $agt_no))
      $valid = false; // Same digit three times consecutively
    elseif (preg_match('/(\d).*?\1.*?\1.*?\1/', $agt_no))
      $valid = false; // Same digit four times in string
  } while ($valid === false);
  return $agt_no;
}

这篇关于PHP 中的随机 ID/数字生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆