How can specific lines be deleted from a text file using PHP?
To delete specific lines from a text file using PHP, you can read the contents of the file, remove the desired lines, and then write the modified content back to the file. One way to achieve this is by reading the file line by line, checking if the line should be deleted, and then writing the remaining lines to a temporary file. Finally, you can replace the original file with the temporary file.
$file = 'example.txt';
$tempFile = 'temp.txt';
$linesToDelete = [2, 4]; // Specify the line numbers to delete
$handle = fopen($file, 'r');
$tempHandle = fopen($tempFile, 'w');
$lineNumber = 1;
while (($line = fgets($handle)) !== false) {
if (!in_array($lineNumber, $linesToDelete)) {
fwrite($tempHandle, $line);
}
$lineNumber++;
}
fclose($handle);
fclose($tempHandle);
unlink($file);
rename($tempFile, $file);
Keywords
Related Questions
- How can PHP developers ensure that user-generated content is moderated effectively to prevent spam or inappropriate submissions?
- What best practices should be followed when setting up session management in PHP to ensure optimal performance and security?
- How can conditional statements be used in PHP to differentiate between administrators and regular users in a table display?