2011-08-15 22 views
0

我原來的測試實現由建築「忽略詞」用下面的代碼數組:進口,分解單詞列表不正確比較

$ignoreList = array("test1", "test2", "test3"); 

後來,我測試在$個別單詞ignoreList:

if(in_array($word, $ignoreList)){ 
    } else{ 
    $words[$word] = $words[$word] + 1; 
} 

此代碼完美工作 - 稍後回顯我的單詞列表時,$ ignoreList中沒有任何單詞出現。我重構,使其更容易添加或刪除的話:

//Import ignore list 
$ignore_raw = file_get_contents("includes/ignore.txt"); 
$ignoreList = explode("\n", $ignore_raw); 

ignore.txt是在其自己的路線,沒有空格的每個項目的純文本文件。進口和爆炸似乎是工作,因爲$ ignoreList導致的print_r聲明:

Array ([0] => a [1] => and [2] => are [3] => as [4] => for [5] => in [6] => is [7] => more [8] => of [9] => than [10] => that [11] => the [12] => to [13] => with) 

比較代碼,然而,停止工作正常,文字忽略列表在我的最終結果顯示再次。任何想法有什麼不對?

+1

什麼的var_dump說?假設你在記事本中創建了txt文件,該文件使用\ r \ n作爲行返回,並且\ r留在每行的末尾。 – erisco

回答

1

您的ignore.txt文件可能有\r\n行結尾,而您的文字實際上有尾隨\r

試一下:

$ignoreList = array_map('trim', file("includes/ignore.txt")); 

BTW你的代碼可能像進行重構:

$words = array_diff($words, $ignoreList); // removes ignored words 
$words = array_count_values($words); // count words 
+0

這樣做。作爲後續行動 - 任何特定的原因print_r不顯示尾隨行結束? –