Ghermans41
Ghermans41

Reputation: 51

How to remove a complete line from a textfile

Hello Stack overflow Currently im having this issue

1105904# (NAME) is banned for 0 Days Unbandate = 2014-01-02 by (Glenn) Banned @ 2014-01-02

When the date is 2014-01-02 it should remove the entire line i tried to use this code

$time = date("Y-m-d");
    $arr = file('ban_list.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $to_remove = $time;
    $arr = array_filter($arr, function($item) use ($to_remove) {
        return $item != $to_remove;
    });
    file_put_contents('ban_list.txt', join("\n", $arr));

It doesnt seem to remove anything

Please help me Greetings Glenn

Upvotes: 0

Views: 67

Answers (2)

evalarezo
evalarezo

Reputation: 1153

Try this with a Linux box:

exec("sed -i '/Unbandate = " . date('Y-m-d') . "/d' ban_list.txt");

EDIT:

A more portable "Windows friendly" way would be:

if ($handle = fopen("ban_list.txt", "c+")) {
    $write_position = ftell($handle);
    while (($line = fgets($handle, 4096)) !== FALSE) {
        $read_position = ftell($handle);
        if (strpos($line, "Unbandate = " . date('Y-m-d')) === FALSE) {
            fseek($handle, $write_position, SEEK_SET);
            fputs($handle, $line);
            $write_position = ftell($handle);
            fseek($handle, $read_position, SEEK_SET);
        }
    }
    ftruncate($handle, $write_position);
    fclose($handle);
}

So with this code is not necessary to create a second file, nor put the whole file in memory. But in the real world, where the memory consumption is always an issue, I still prefer my first solution, or some kind of Windows variant, something like this (untested) code:

exec("cat ban_list.txt | where { $_ -notmatch 'Unbandate = " . date('Y-m-d') . "' } > ban_list.txt");

Upvotes: 0

Sbls
Sbls

Reputation: 495

You check if the whole line is equal to $time. Make a regex out of it or check with strpos. But make sure you don't remove the line because the creation date is the current date.

The following works for example

array_filter($arr, function($item) use ($to_remove) {
     return !preg_match("/$to_remove by /", $item);
});

The whole script:

$time = date("Y-m-d");
$arr = file('ban_list.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$to_remove = $time;
$arr = array_filter($arr, function($item) use ($to_remove) {
    return !preg_match("/$to_remove by /", $item);
});
file_put_contents('ban_list.txt', join("\n", $arr));

Upvotes: 1

Related Questions