我想取一個陣列的隨機字串,并且應該計算隨機字串的輔音。問題是它沒有計算 array_rand() 中的字母這是我此時得到的:
<?php
$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.";
?>
uj5u.com熱心網友回復:
您正在測驗整個單詞是否在輔音陣列中,而不是計算每個字符。您需要遍歷字符。
$word = $woerter[$random];
for ($i = 0; $i < strlen($word); $i ) {
if (in_array($word[$i], $konsonanten)) {
$zaehler ;
}
}
uj5u.com熱心網友回復:
寫出一整套列入白名單的輔音似乎比我更喜歡撰寫代碼更乏味。對每個角色進行回圈呼叫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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/537870.html
標籤:PHP
上一篇:設定直方圖的x和y值
