2017-02-28 55 views
0

我试图在PHP中找到字符串中最常用的字。歌词文件是一串歌词。如何在字符串中找到最常用的字PHP

  //display the most used word in the lyrics file 
     $wordCount = str_word_count($lyrics); 
     $wordCountArray = array(); 
     foreach($wordCount as $word){ 
      if(!array_key_exists($word, $wordCountArray)){ 
       $wordCountArray[$word] = 1; 
      }else{ 
       $wordCountArray[$word] += 1; 
      } 
     } 
     arsort($wordCountArray); 
     print_r($wordCountArray[0]); 

我得到这段代码的错误,我想知道什么是不工作。我需要实际的单词而不是数字。

+0

什么是你的问题? – Marcel

+0

这可能取决于'$ lyrics'是什么。你可能需要提供一个例子。 –

+0

http://php.net/manual/en/function.substr-count.php可能会有所帮助 – meen

回答

1

我想你的意思是:

$words = str_word_count($lyrics, 1) 
foreach($words as $word) { 
0

简单的例子

<?php 
    $string = 'Hello hi hello abcd abc hoi bye hello'; 

    $string = strtolower($string); 
    $words = explode(' ',$string); 
    var_dump(array_count_values($words)); 
相关问题