我有一个PHP函数,可以生成给定长度的字母数字字符串。功能正常。但生成的字符串有时包含数字,有时它不包括数字。我希望字符串每次都必须由数字和alpha组成。需要提出建议。这是函数的代码:
public static function GenerateAlphaNumString($length=0) {
$characterPool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characterPool[rand(0, strlen($characterPool) - 1)];
}
return $randomString;
}
答案 0 :(得分:4)
一个完整的例子,提供灵活性:
<?php
class StringGenerator
{
private $characterPool = [
'numeric' => '0123456789',
'alpha' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
];
function generateRandomString($length, $pool) {
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $this->characterPool[$pool][rand(0, strlen($this->characterPool[$pool]) - 1)];
}
return $randomString;
}
function generateAlphaNumString($length=0, $numeric=0) {
return str_shuffle(
$this->generateRandomString($numeric, 'numeric') .
$this->generateRandomString($length-$numeric, 'alpha')
);
}
}
$generator = new StringGenerator;
for ($c=0; $c<=10; $c++) {
var_dump($generator->generateAlphaNumString(10, 5));
}
输出类似于:
string(10) "J5F4FQX480"
string(10) "Z2g647pO9a"
string(10) "159Mf8GEL3"
string(10) "B5P57I42hN"
string(10) "Us97v5cg80"
string(10) "34VEHY825t"
string(10) "V6Ei5p06s1"
string(10) "YS5noD5127"
string(10) "4dJ4Y4G4q4"
string(10) "C8V7W3Q2G9"
string(10) "gu28g99H9d"
答案 1 :(得分:3)
这应该可以解决问题
$characterPool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
$numberscount = rand(1,$length-1);
for ($i = 0; $i < $numberscount; $i++) {
$randomString .= rand(0,9);
}
for ($i = 0; $i < ($length - $numberscount); $i++) {
$randomString .= $characterPool[rand(0, strlen($characterPool) - 1)];
}
当$ length = 1时,它总是打印一个字符。
答案 2 :(得分:3)
你可以这样做:
// Add a quick exit:
if ($length <= 0) return '';
// Produce all characters except the last one:
for ($i = 0; $i < $length-1; $i++) {
$randomString .= $characterPool[rand(0, strlen($characterPool) - 1)];
}
// Check if string contains a digit, if not, reduce range
// for generating last character so it can only be a digit:
$lastRange = preg_match("/\d/", $randomString) ? strlen($characterPool) : 10;
// choose random position, and insert last character in there:
$randomString = substr_replace($randomString, $characterPool[rand(0, $lastRange-1)],
rand(0, $length-1), 0);
return $randomString;
此方法将保持每个字符出现的概率尽可能接近原始字符。它不会强制将数字组合在一起。
显然,只有当给定长度至少为2时,才能生成正确的混合。
答案 3 :(得分:2)
在返回字符串
之前添加以下内容If(!preg_match( '/([0-9]+)/', $randomString) {
return self::GenerateAlphaNumString($length);
}
如果你的字符串中没有数字,只需调用相同的函数,直到有。