What is the best practice for deleting a specific line in a .txt file using PHP?
When deleting a specific line in a .txt file using PHP, one approach is to read the file line by line, skip the line that needs to be deleted, and then rewrite the remaining lines to a new file. Once the new file is complete, it can replace the original file to effectively delete the specified line.
$filename = 'example.txt';
$line_number = 3; // Line number to delete
$lines = file($filename, FILE_IGNORE_NEW_LINES);
unset($lines[$line_number - 1]);
$new_content = implode("\n", $lines);
file_put_contents($filename, $new_content);
Keywords
Related Questions
- Is it advisable to restrict access to a website based on referrer or user agent information in PHP, considering potential implications for legitimate users and search engine crawlers?
- How can defining constants in PHP help prevent errors and improve code readability, especially when dealing with string values like "Alle"?
- Are there specific considerations to keep in mind when using batch files to create PHP files with special characters?