In my PHP project I am trying to calculate average words count per sentence.
When I input few sentences everything works as it should.
Sentence:
"content": "Cassieres Werk zur der verbindet die des mit an."
Result:
"wordsPerSentences": "9.0"
BUT, when I input just one sentence and without full stop the average value is "0".
Content:
"content": "Cassieres Werk zur der verbindet die des mit an"
Result:
"wordsPerSentences": "0.0"
Also, problem is that when I input 'full stop' and space it adds to the score or comma and space after the word?
Content:
"content": "Cassieres Werk zur der, verbindet die des mit an. "
Result:
"wordsPerSentences": "10.0"
How can I cover that condition among others?
EDIT: This conditions are solved except the one where there is "comma" between just two words in a sentence, it returns "1", and should "2".
My code:
$tokens = ',.;';
$sentences = [];
$chunk = strtok(trim($text), $tokens);
// Handle empty $text
if (!is_string($chunk)) {
return 0;
}
do {
$sentences[] = $chunk;
} while ($chunk = strtok($tokens));
$countWords = function (int $carry, string $item) {
return $carry + count(array_filter(explode(' ', $item)));
};
$totalWords = array_reduce($sentences, $countWords, 0);
return $totalWords / count($sentences);