Delete duplicate data in text file with php

I need to open a text file (file.txt) that contains data in the following format

ai bt bt gh ai gh lo ki ki lo 

Ultimately, I want to delete all duplicate rows, so that only one of this data remains. Thus, the result will look like this:

 ai bt gh lo ki 

any help with this would be awesome

+4
source share
4 answers

This should do the trick:

 $lines = file('file.txt'); $lines = array_unique($lines); 

file() reads the file and puts each line in an array.

array_unique() removes duplicate elements from an array.

In addition, to return everything to a file:

 file_put_contents('file.txt', implode($lines)); 
+16
source

Take file php file function () to read the file. You get an array of strings from your file. After that, take array_unique to print the duplicates.

In the end, you will have something like

 $lines = array_unique(file("your_file.txt")); 
+2
source

This might work:

 $txt = implode('\n',array_unique(explode('\n', $txt))); 
0
source
 $lines = file_get_contents('file.txt'); $lines = explode('\n', $lines); $lines = array_unique($lines); $lines = implode('\n', $lines); file_put_contents('file.txt', $lines); 
0
source

Source: https://habr.com/ru/post/1446057/


All Articles