这个孤立的问题可以使用 php 的array_* 函数来解决。
-
首先,让我们定义变量:
$letters = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
$min_length = 5;
$max_length = 15;
$must_include = array('a','e', 't', '7');
$must_exclude = array('4','q', 'j', '9');
-
为了更简单的解决方案,让我们根据$min_length 和$max_length 值定义一个固定长度的结果作为变量:
$actual_length = rand($min_length, $max_length);
-
下一步,让我们通过删除and来准备干净的字母:
$clean_letters = array_diff($letters, $must_exclude);
$clean_letters = array_diff($letters, $must_include);
请注意,我删除$must_include 和$must_exclude 的原因是,稍后我将在结果中包含$must_include,因为它必须包含在内。
-
现在来看实际结果:
$result = $must_include;
$result = array_merge($result, array_rand($letters, $actual_length - sizeof($result)));
在这一步中,我默认$result 为$must_include,然后将其与$letters 的随机值合并为$actual_length 的大小减去$must_include 的大小。
上述所有步骤将产生在$must_include 中始终包含字母并省略$must_exclude 字母的值。
完整脚本如下:
<?php
$letters = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
$min_length = 5;
$max_length = 15;
$must_include = array('a','e', 't', '7');
$must_exclude = array('4','q', 'j', '9');
$actual_length = rand($min_length, $max_length);
echo "Length: " . $actual_length . ".\n";
if( count(array_intersect($must_include, $must_exclude)) > 0 ){
die("Value in $must_include MUST NOT present in $must_exclude.\n");
}
if( count(array_intersect($must_exclude, $must_include)) > 0 ){
die("Value in $must_exclude MUST NOT present in $must_include.\n");
}
if(sizeof($must_include) > $min_length){
die("\$min_length MUST BE larger or equal to \$must_include.\n");
}
if(!$actual_length <= $max_length || $actual_length >= $min_length){
} else {
die("\$actual_length MUST BE between \$min_length to \$max_length.\n");
}
$clean_letters = array_diff($letters, $must_exclude);
$clean_letters = array_diff($letters, $must_include);
// echo implode(", ", $clean_letters) . "\n";
$result = $must_include;
$result = array_merge($result, array_rand($letters, $actual_length - sizeof($result)));
echo "Must Include: " . implode(", ", $must_include) . "\n";
echo "Must Exclude: " . implode(", ", $must_exclude) . "\n";
echo "Result (" . sizeof($result) . "): " . implode(", ", $result) . "\n";