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?
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.
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 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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With