根据字长计算单词数

时间:2014-05-22 10:57:07

标签: php

我需要一个PHP函数来计算文本中1,2,3,4等字母的单词数量

案文是:

$lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam mollis urna nisl, ut euismod purus adipiscing vitae. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent ultricies risus non arcu bibendum tempor."

例如:

Number of words with 1 letter is: ....
Number of words with 2 letters is: ....
Number of words with 3 letters is: ....

2 个答案:

答案 0 :(得分:1)

试试这个

$lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam mollis urna nisl, ut euismod purus adipiscing vitae. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent ultricies risus non arcu bibendum tempor.";

$arr = explode(" ",$lorem);

$arr_count = array();
foreach($arr as $val)
{
    $key = strlen($val);
    if(isset($arr_count[$key]))
    {
        $arr_count[$key]+=1;
    }   
    else
    {
        $arr_count[$key] =1;    
    }
}
ksort($arr_count);
foreach($arr_count as $key=>$val)
{
    echo "Number of words with ".$key." letter is:".$val."<br/>";
}

输出:

Number of words with 2 letter is:1
Number of words with 3 letter is:4
Number of words with 4 letter is:2
Number of words with 5 letter is:13
Number of words with 6 letter is:2
Number of words with 7 letter is:2
Number of words with 8 letter is:2
Number of words with 9 letter is:1
Number of words with 10 letter is:3
Number of words with 11 letter is:2

参见 DEMO

答案 1 :(得分:0)

你可以这样做:

foreach(explode(' ',$lorem) as $word)
    $arr[strlen($word)] = isset($arr[strlen($word)]?$arr[strlen($word)]+1:1);

现在$arr是一个数组。数组的键是字母数。数组的值是相应的单词数。