What is the best approach to search for and delete a specific line in a text file using PHP?
To search for and delete a specific line in a text file using PHP, you can read the contents of the file, search for the specific line, remove it from the array of lines, and then rewrite the modified content back to the file.
<?php
$filename = 'example.txt';
$line_to_delete = 'Specific line to delete';
// Read the file into an array of lines
$lines = file($filename);
// Search for the specific line and remove it
$index = array_search($line_to_delete, $lines);
if($index !== false) {
unset($lines[$index]);
}
// Write the modified content back to the file
file_put_contents($filename, implode('', $lines));
?>
Keywords
Related Questions
- What are the implications of copying variables unnecessarily in PHP, and how does it impact memory consumption?
- What are the potential reasons for receiving "$KUNDENNR" instead of the desired output when trying to display PHP data in HTML?
- What are the advantages and disadvantages of using the Apigility framework for PHP?