2017-02-28 63 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)); 
相關問題