dqf42223 2013-09-07 07:17
浏览 58
已采纳

在字符串中出现最多的Php单词

I'm supposed to find to word in sentence that appears the most.

This is what I've tried and it doesn't work.

<?php
$str = "Hello friend, Hello good  good today!";
$time=array();
$cnt=str_word_count($str, 1);
$times=reset($cnt);
$count=0;
foreach($cnt as $val){
    $times=$val;    
    foreach($cnt as $val){
        if($times===$val){
            $count++;
            $times=$times . $count;     
        }       
    }
    $count=0;
}
print_r($cnt);
print_r($times);    
  • 写回答

3条回答 默认 最新

  • duangutian1426 2013-09-07 07:48
    关注
    <?php
    $str = "Hello friend, Hello good  good today!";
    $count = array();
    $words = array();
    $cnt = str_word_count($str, 1);
    foreach ($cnt as $val){
        $i = 0;
        $term = false;
        foreach ($words as $word){
            if ($word === $val){
                $count[$i]++;
                $term = true;
                break;
            }
            $i++;
        }
        if ($term)
            continue;
        $words[$i] = $val;
        $count[$i] = 1;
    }
    print_r($cnt);
    print_r('<br/>');
    $max = -1;
    $resultWords = array();
    $resultCount = array();
    $i = 0;
    foreach ($count as $c){
        if ($max == $c){
            $resultWords[] = $words[$i];
            $resultCount[] = $c;
        }else if ($max < $c){
            $resultWords = array();
            $resultCount = array();
            $resultWords[] = $words[$i];
            $resultCount[] = $c;
            $max = $c;
        }
        $i++;
    }
    foreach ($resultWords as $result){
        print_r($result.' '.$max.'<br/>');
    }
    ?>
    

    try using my code above. Hope it will work. If the most recurring word is only one word, then that word along with number of occurrence of that word will be display. If there is more than one word, all that words will be displayed as long as the number of occurrence.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?