Answer the question
In order to leave comments, you need to log in
How to count the number of words of the same length?
Good evening. You need to write a function that counts the number of words in a sentence and the number of letters in a word.
For example: I am going to the cinema, who is with me? (1-2, 2-1, 3-2, etc.) i.e. 1 character 2 words (I, c), 3 characters 2 words (I go, who) and in this vein.
Found some code:
$Str = "Шел дождь, автобус мокрый, все спят, или не все";
$pieces = explode(" ", $Str);
foreach($pieces as $val)
$pos[$val] = substr_count($Str, $val);
foreach($pos as $key => $cal)
{
echo "Кол-во повторений: $key = $cal<br>";
}
Answer the question
In order to leave comments, you need to log in
function wordsCounter(string $text)
{
$text = str_replace(["!","...","?"],".",$text);// приводим окончания предложений к одному формату
$text = str_replace([",","-"],"",$text); // чистим текст от знаков кроме .
$sentances = explode(".",$text);
$result = [];
foreach($sentances as $sentance)
{
$words = explode(" ", $sentance);
foreach ($words as $word)
{
$length = mb_strlen($word);
if(empty($result[$length]))
$result[$length] = 1;
else
$result[$length] += 1;
}
}
return $result;
}
$text = "я иду в кино, кто со мной?";
print_r(wordsCounter($text));
$input = <<<EOL
Добрый вечер. Нужно написать функцию, которая считает количество слов в предложении и букв в слове.
Например: я иду в кино, кто со мной? (1-2, 2-1, 3-2, и тд) т.е. по 1 символу 2 слова (я,в), по 3 символа 2 слова(иду, кто) и в таком ключе.
Нашел некоторый код:
EOL;
$input = str_replace(["\n", "\r"], ' ', $input);
$words = explode(' ', $input);
$len = [];
$reg = '/^[^А-Яа-я]*([А-Яа-я]|[А-Яа-я]+.*[А-Яа-я]+)[^А-Яа-я]*$/';
$callback = function(array $m) use (&$len)
{
$length = mb_strlen($m[1]);
$len[$length][] = $m[1];
return '';
};
$words = preg_replace_callback($reg, $callback, $words);
var_dump($len);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question