问题描述
我有我试图删除重复行的文本文件。
I have a text file which I am trying to remove duplicate lines.
文本文件的例子:
new featuredProduct('', '21640'),
new featuredProduct('', '24664'),
new featuredProduct('', '22142'),
new featuredProduct('', '22142'),
new featuredProduct('', '22142'),
new featuredProduct('', '22142'),
new featuredProduct('', '22142'),
的PHP code我试过:
$lines = file('textfile.txt');
$lines = array_unique($lines);
file_put_contents('textfile.txt', implode($lines));
的PHP文件名为duplicates.php和文本文件在同一目录下。我想将只剩下:
The PHP file is called duplicates.php and the textfile is in the same directory. I would like to be left with only:
new featuredProduct('', '21640'),
new featuredProduct('', '24664'),
new featuredProduct('', '22142'),
文件函数试图将文件读入$线阵列则array_unique()来删除重复的条目。然后将过滤的结果发回在同一文件中。
The file function is trying to read the file into the $lines array then array_unique() to remove the duplicate entries. Then put the filtered results back in the same file.
推荐答案
问题是在每行末尾的新行字符。因为你没有在最后一行的末尾有一个新行字符它不会一样其他
The problem is the new line characters at the end of each line. Because you don't have a new line character at the end of the last line it won't be the same as the others.
在读取该文件,然后添加然后当你再次保存文件,以便只是删除它们:
So just remove them when you read the file and then add then when you save the file again:
$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($线);在
呼叫你会看到它在
正确的文件()
If yo do: var_dump($lines);
right after the file()
call you will see it:
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
}
这篇关于删除文本文件中重复的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!