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);