【问题标题】:PHP: Generating random string with both suffix and prefix as capital lettersPHP:生成带有后缀和前缀作为大写字母的随机字符串
【发布时间】:2012-07-09 00:09:36
【问题描述】:

大家好,我想创建一个随机数字字符串,其中开头有一个固定字母 B,一组八个整数以任意随机字母结尾,例如 B07224081A,其中 A 和其他数字是随机的。这个字符串应该是唯一的。我该怎么做?

【问题讨论】:

  • 这不是 cakephp 特定的问题。只是好的旧PHP。非常相似:stackoverflow.com/questions/853813/…
  • 完全正确.. 只需谷歌搜索如何生成随机字母数字字符串并根据您的目的修改脚本!

标签: php


【解决方案1】:

你的意思是这样的吗?

$letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$numbers = rand(10000000, 99999999);
$prefix = "B";
$sufix = $letters[rand(0, 25)];

$string = $prefix . $numbers . $sufix;
echo $string; // printed "B74099731P" in my case

字符越多 - 生成唯一字符串的机会就越大。

我认为使用uniqid() 的方法要好得多,因为它基于毫秒。保证生成字符串的唯一性。

【讨论】:

  • 为了真正保证唯一性,您需要跟踪您使用过的字符串,并在遇到重复时重新生成。
【解决方案2】:

这应该适合你。

  $randomString = "B";
  for ($i = 0; $i < 9; $i++) {
    if ($i < 8) {
        $randomString.=rand(0,9);
    }  
    if ($i == 8) {
        $randomString.=chr(rand(65,90));
    }
  }
  echo $randomString;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多