我如何找到特定数字的单词的出现

问题描述 投票:1回答:2

大家好,我有一个小问题,假设我有一个字符串为

“你好,我叫XYZ”

现在,我知道我可以找到单词的长度,因为“ Hello”有5个字符,“ My”有2个字符。通过使用以下代码

$text = file_get_contents('text.txt'); // $text = 'Hello my name is XYZ';
$words = str_word_count($text, 1);
$wordsLength = array_map(
function($word) { return mb_strlen($word, 'UTF-8'); },
$words
);

var_dump(array_combine($words, $wordsLength));

但是如果我想发现长度为1的单词数为0。长度为2的单词数为2。长度为3的单词数为1,依此类推,直到长度为10的数量

注-我正在考虑单词长度,直到有一个空格。假设数据中有一个日期,如20.04.2016,它应该告诉我数字是长度为10的单词为1。

还有另一件事,我如何找到字符串中单词的平均长度。预先谢谢你

php string word-count
2个回答
0
投票
$counts = array_replace(array_fill(1, 9, 0), array_count_values($wordsLength));

会给...

Array
(
    [1] => 0
    [2] => 2
    [3] => 1
    [4] => 1
    [5] => 1
    [6] => 0
    [7] => 0
    [8] => 0
    [9] => 0
)

1
投票
$text = 'Hello 20.04.2016 🚩 my face😘face is XYZ'; $words =preg_split('/\s+/', $text); $wordsLength = array_map( function($word) { return mb_strlen($word, 'UTF-8'); } ,$words); print_r($words); //Get Average word Length $avg=round(array_sum($wordsLength)/count($words),1); //print Avg print($avg); ?>
© www.soinside.com 2019 - 2024. All rights reserved.