Remove duplicate data in a text file with php

后端 未结 4 635
半阙折子戏
半阙折子戏 2021-02-03 15:02

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

ai
bt
bt
gh
ai
gh
lo
ki
ki
lo

ultimately I want to remo

相关标签:
4条回答
  • 2021-02-03 15:09
    $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 讨论(0)
  • 2021-02-03 15:15

    This should do the trick:

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

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

    array_unique() removes duplicate elements from the array.

    Also, to put everything back into the file:

    file_put_contents('file.txt', implode($lines));
    
    0 讨论(0)
  • 2021-02-03 15:21

    This might work:

    $txt = implode('\n',array_unique(explode('\n', $txt)));
    
    0 讨论(0)
  • 2021-02-03 15:30

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

    In the end, you will have something like

    $lines = array_unique(file("your_file.txt"));
    
    0 讨论(0)
提交回复
热议问题