How to delete a line from the file with php?

It can be solved without the use of awk:

function remove_line($file, $remove) {
    $lines = file($file, FILE_IGNORE_NEW_LINES);
    foreach($lines as $key => $line) {
        if($line === $remove) unset($lines[$key]);
    }
    $data = implode(PHP_EOL, $lines);
    file_put_contents($file, $data);
}

this will just look over every line and if it not what you want to delete, it gets pushed to an array that will get written back to the file. see this

 $DELETE = "the_line_you_want_to_delete";

 $data = file("./foo.txt");

 $out = array();

 foreach($data as $line) {
     if(trim($line) != $DELETE) {
         $out[] = $line;
     }
 }

 $fp = fopen("./foo.txt", "w+");
 flock($fp, LOCK_EX);
 foreach($out as $line) {
     fwrite($fp, $line);
 }
 flock($fp, LOCK_UN);
 fclose($fp);  

Read the lines one by one, and write all but the matching line to another file. Then replace the original file.


$contents = file_get_contents($dir);
$contents = str_replace($line, '', $contents);
file_put_contents($dir, $contents);

Tags:

Php

File

Awk

Line