PHP fopen() / fwrite() help

Started on the old forum in March 2013 · view the original in the archive · old links redirect here

3 replies · 458 views · started 13 years ago · 1 min read

3 participants
Christian Cepe Newbie · 7 posts #1

How to remove multiple lines in txt file using fwrite/fopen method? This is my .txt file

One
Two
Three
One
Four
Five
Three
Eight

I want to remove those repeated lines (One & Three)

Help me, thanks!

Rksk Developer · 54 posts #2

I think, you can't do it directly with only fopen & fwrite. You have to get whole file into an array, clean repeated items and overwrite whole with new data.

CreativityKills Lead · 833 posts #3

I don't really understand what you want to achieve but...

$chop_lines = array(4, 7);

$file = "path/to/file.txt";

$data = file_get_contents($file);

$data_array = explode("\n", $data);

foreach ($chop_lines as $line)
{
    $line = (int) $line - 1;

    if(isset($data_array[$line])) unset($data_array[$line]);
}

$data = implode("\n", $data_array);

file_put_contents($file);

If on the other hand u wanna keep only unique entries, u could probably do something like...

$file = "path/to/file.txt";

$data = file_get_contents($file);

$data_array = explode("\n", $data);

$data_array = array_unique($data_array);

$data = implode("\n", $data_array);

file_put_contents($file);

Sign in to reply.

Similar topics

Keyboard shortcuts

g f
Go to forums
g h
Go to your feed
g m
Go to messages
r
Reply (in a topic)
/
Search
j
Next post
k
Previous post
?
This list
Ctrl/⌘ + Enter
Send what you are writing
Ctrl/⌘ + B / I
Bold / italic while writing
Esc
Close