2015-05-22 38 views
4

我有一個文本文件,我試圖刪除重複的行。刪除文本文件中的重複行

文本文件,例如:

new featuredProduct('', '21640'), 
new featuredProduct('', '24664'), 
new featuredProduct('', '22142'), 
new featuredProduct('', '22142'), 
new featuredProduct('', '22142'), 
new featuredProduct('', '22142'), 
new featuredProduct('', '22142'), 

PHP代碼我已經試過:

$lines = file('textfile.txt'); 
$lines = array_unique($lines); 
file_put_contents('textfile.txt', implode($lines)); 

的PHP文件名爲duplicates.php和文本文件是在同一目錄。我想將只剩下:

new featuredProduct('', '21640'), 
new featuredProduct('', '24664'), 
new featuredProduct('', '22142'), 

文件函數試圖將文件讀入$線陣列然後array_unique()來刪除重複項。然後將過濾的結果放回到同一個文件中。

+1

看起來不錯,您發佈的問題是什麼? – vivoconunxino

+0

您的代碼有效。也許用'file_put_contents('textfile.txt',$ lines)取代最後一行;' – Med

+0

也許這就是你想要的? 'file_put_contents('textfile.txt',implode(PHP_EOL,$ lines));' – Augwa

回答

7

問題是每行結尾的新行字符。因爲在最後一行末尾沒有換行符,所以不會與其他行相同。

所以只要刪除它們,當你閱讀該文件,然後添加然後當你再次保存文件:

$lines = file('test.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); 
$lines = array_unique($lines); 
file_put_contents('test.txt', implode(PHP_EOL, $lines)); 

如果喲信息:後var_dump($lines);file()叫你會看到它:

array(7) { 
    [0]=> 
    string(36) "new featuredProduct('', '21640'), 
" 
    [1]=> 
    string(36) "new featuredProduct('', '24664'), 
" 
    [2]=> 
    string(36) "new featuredProduct('', '22142'), 
" 
    [3]=> 
    string(36) "new featuredProduct('', '22142'), 
" 
    [4]=> 
    string(36) "new featuredProduct('', '22142'), 
" 
    [5]=> 
    string(36) "new featuredProduct('', '22142'), 
" 
    [6]=> 
    string(34) "new featuredProduct('', '22142'), " 
     //^^ See here       ^And here 
} 
+0

優秀的答案Rizier123。非常感謝先生。謝謝 – Hexana

+0

@Hexana不客氣。祝你有個愉快的一天:)(你知道我現在可以說,我使用file()中的標誌是有原因的:http://stackoverflow.com/a/30350862 :) – Rizier123

0

試試這個

$string = file_put_contents('textfile.txt'); 
$splitstr = explode('),', $string); 
$str = implode('),',array_unique($splitstr)); 
var_dump($str); 
2

我知道這個問題是關於PHP,我不知道你是使用Linux/Unix還是Windows,但是有一個非常好的bash解決方案可以擺脫重複文件,這對我認爲的大文件來說會更快。您甚至可以通過系統調用從PHP執行它:

awk '!a[$0]++' input.txt