我正在编写一个函数来计算一个单词的音节,如下所示:
function estimate_syllables($word) {
$total_count=0;
foreach($word as $w) {
$syllable_count = count_english_vowels($w);
$total_count += $syllable_count;
}
return $total_count;
}
function count_english_vowels($word) {
static $english_vowels = array('A', 'E', 'I', 'O', 'U', 'Y');
$vowel_count = 0;
$letters = preg_replace('/[^a-z0-9]+/i', "", $word);
$len = strlen($letters);
$letters = str_split(strtoupper($letters));
$currPosition = -2;
$prevPosition = -1;
for($i = 0; $i < $len; $i++) {
if (in_array($letters[$i], $english_vowels)) {
if($i != $currPosition + 1) {
if ($letters[$i] == 'E' && $i != ($len -1))
$vowel_count++;
$prevPosition = $currPosition;
$currPosition = $i;
}
}
}
return $vowel_count;
}
我真的很困惑:如果你把count_english_vowels传递给像水一样的单词,它会到达内循环到正确的音节两次,但是计数器只报告1?超级困惑,任何人都可以弄清楚出了什么问题?
答案 0 :(得分:2)
由于这个原因,它只报告一个:
if ($letters[$i] == 'E' && $i != ($len -1))
$vowel_count++;
$prevPosition = $currPosition;
$currPosition = $i;
E
中只有一个water
,因此它只执行一次$vowel_count++;
。根据你对这段代码的缩进,我假设你需要{}
括号围绕这些行,因为没有它们PHP只会在if之后应用第一个行,所以如果没有代码是正确的你的缩进应该是这样的:
if ($letters[$i] == 'E' && $i != ($len -1))
$vowel_count++;
$prevPosition = $currPosition;
$currPosition = $i;