计数在数组中随机找到的单词中的辅音



我想取数组的一个随机字符串,并且应该计算随机字符串的辅音。问题是它没有计算来自array_rand()的字母。

这里是我得到的结果:

$woerter = [
"Maus",
"Automobil",
"Schifffahrt",
"Hund",
"Katze",
"Ziege",
"Stanniolpapier",
"Elefant",
"Isopropylalkohol",
"Schwimmbad"
];
$random = array_rand($woerter);
$konsonanten = ["b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","u","v","w","x","y","z",
"B","C","D","F","G","H","J","K","L","M","N","P","Q","R","S","T","U","V","W","X","Y","Z"];
$zaehler = 0;
if (in_array($woerter[$random], $konsonanten)) {
$zaehler++;
}
echo "Das Wort "$woerter[$random]" enthält $zaehler Zeichen, die keine Vokale sind.";

您正在测试整个单词是否在辅音数组中,而不计算每个字符。你需要遍历这些字符。

$word = $woerter[$random];
for ($i = 0; $i < strlen($word); $i++) {
if (in_array($word[$i], $konsonanten)) {
$zaehler++;
}
}

写出一个完整的白名单辅音数组似乎更乏味,我更愿意编码。在每个角色上循环调用in_array()对我来说也不是很聪明/有效。

考虑仅仅去掉所有的元音,然后计算剩下的。请注意,如果您的单词可能包含多字节/重音字符,您也需要适应这种可能性。mb_strlen()也可能是必要的(而不是strlen())。

代码(演示):

foreach ($woerter as $word) {
echo "Consonants found in $word: " . strlen(str_ireplace(['a', 'e', 'i', 'o', 'u'], '', $word)) . "n";
}

输出:

Consonants found in Maus: 2
Consonants found in Automobil: 4
Consonants found in Schifffahrt: 9
Consonants found in Hund: 3
Consonants found in Katze: 3
Consonants found in Ziege: 2
Consonants found in Stanniolpapier: 8
Consonants found in Elefant: 4
Consonants found in Isopropylalkohol: 10
Consonants found in Schwimmbad: 8

最新更新