Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a line from the file with php?

Tags:

I have a file named $dir and a string named $line, I know that this string is a complete line of that file but I don't know its line number and I want to remove it from file, what should I do?

Is it possible to use awk?

like image 377
ibrahim Avatar asked Apr 19 '11 07:04

ibrahim


People also ask

How to delete file content in PHP?

In PHP, we can delete any file using unlink() function. The unlink() function accepts one argument only: file name. It is similar to UNIX C unlink() function. PHP unlink() generates E_WARNING level error if file is not deleted.

Can PHP delete a file?

To delete a file in PHP, use the unlink function. Let's go through an example to see how it works. The first argument of the unlink function is a filename which you want to delete. The unlink function returns either TRUE or FALSE , depending on whether the delete operation was successful.

How do I overwrite a file in PHP?

How to overwrite file contents with new content in PHP? 'w' -> Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. 'w+'-> Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length.


3 Answers

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

like image 197
Ignacio Vazquez-Abrams Avatar answered Nov 16 '22 23:11

Ignacio Vazquez-Abrams


$contents = file_get_contents($dir);
$contents = str_replace($line, '', $contents);
file_put_contents($dir, $contents);
like image 30
Naveed Ahmad Avatar answered Nov 16 '22 23:11

Naveed Ahmad


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);  
like image 29
Thusitha Sumanadasa Avatar answered Nov 17 '22 01:11

Thusitha Sumanadasa