我必须写一个程序,输出随机单词(带有随机字母),并且附近不会有3个人声或辅音,所以我写了:
$array = array();
$n = 10;
for($i = 0; $i < $n; $i++) {
$l = rand(4, 10); //$l = word length
?>
<br>
<?
for ($j = 0; $j < $l; $j++) {
$cas = rand(65, 90); //$cas=random letters
$array[$j] = $cas;
if($j > 1) {
if (($array[$j-1] == 65 || $array[$j-1] == 69 || $array[$j-1] == 73 || $array[$j-1] == 79 || $array[$j-1] == 85) ^ ($array[$j-2] == 65|| $array[$j-2] == 69 || $array[$j-2] == 73 || $array[$j-2] == 79 || $array[$j-2] == 85)) { //will do XOR '^'
$cas = rand(65, 90);
$array[$j] = $cas;
}
}
$m = chr($array[$j]);
echo $m;
}
}
?>
</body>
</html>
不知道为什么,但IF似乎不起作用,因为当它输出时,它也会打印有3个或更多辅音或元音的单词。有人能帮我吗?谢谢:D,抱歉英语不好:P
这应该适用于您:
那么我在这里做了什么?
在第一部分中,我定义了包含所有字符的数组$characters
,例如[a-zA-Z]
。那么我还有包含所有元音的$vowels
,例如[aAeEiIoOuU]
。我还定义了包含所有辅音的$consonants
。
之后,我将整个$characters
阵列与shuffle()
混合,并从一开始就使用array_slice()
获取$length
阵列元素。
然后,我用函数check()
检查了$randomWord
,它遍历随机单词的每个字符,并检查接下来的3个字符是元音还是辅音。我使用in_array()
来检查字符是否在相关联的数组中,例如$vowels
或$consonants
。如果是,我将行的中间字符改为相反的字符,例如vowels
->consonants
|consonants
->vowels
。如果没有找到元音或辅音的行,则返回随机单词。
最后,我只使用array_map()
和chr()
来遍历每个数组元素,并将其从ASCII更改为匹配字符。
为了打印它,我使用implode()
将每个字符附加在一起。
<?php
$characters = array_merge(range(65, 90), range(97, 122));
$vowels = array(65, 97, 69, 101, 73, 105, 79, 111, 85, 117);
$consonants = array(66, 98, 67, 99, 68, 100, 70, 102, 71, 103, 72, 104, 74, 106, 75, 107, 76, 108, 77, 109, 78, 110, 80, 112, 81, 113, 82, 114, 83, 115, 84, 116, 86, 118, 87, 119, 88, 120, 89, 121, 90, 122);
$randomWord = "";
$length = rand(4, 10);
shuffle($characters);
$randomWord = array_slice($characters, 0, $length);
function check($randomWord, $vowels, $consonants) {
foreach($randomWord as $key => $randomCharacter) {
//Check for vowels
if(in_array($randomWord[$key], $vowels) && ( isset($randomWord[$key+1]) && in_array($randomWord[$key+1], $vowels) ) && ( isset($randomWord[$key+2]) && in_array($randomWord[$key+2], $vowels) )) {
$randomWord[$key+1] = $consonants[array_rand($consonants, 1)];
check($randomWord, $vowels, $consonants);
}
//Check for consonants
if(in_array($randomWord[$key], $consonants) && ( isset($randomWord[$key+1]) && in_array($randomWord[$key+1], $consonants) ) && ( isset($randomWord[$key+2]) && in_array($randomWord[$key+2], $consonants) )) {
$randomWord[$key+1] = $vowels[array_rand($vowels, 1)];
check($randomWord, $vowels, $consonants);
}
}
return $randomWord;
}
$randomWord = check($randomWord, $vowels, $consonants);
echo $randomWord = implode("", array_map("chr", $randomWord));
?>
示例输出:
YeVIkufuhv
lEMObi
VosaKAzIRb
qOyoK
IBoVIQahIg
这段代码对我来说是私有的,你可以使用它
function random_string($hashstring=null,$randLengh=null)
{
$string = $hashstring;
$randLengh =$randLengh;
if ($string == null) {
$string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
}
$charactersLength = strlen($string);
$randomString = '';
for ($i = 0; $i < $randLengh; $i++) {
$randomString .= $string[rand(0, $charactersLength - 1)];
}
return $randomString;
}