How can one search for a specific string in a text file and delete all lines below it in PHP?

To search for a specific string in a text file and delete all lines below it in PHP, you can read the file line by line, check if the specific string is found, and then write only the lines above it to a new file. Once the specific string is found, you can stop writing lines to the new file.

$specificString = "example"; // specify the string to search for
$filename = "input.txt"; // specify the input file
$outputFilename = "output.txt"; // specify the output file

$found = false;
$lines = file($filename);
$output = fopen($outputFilename, "w");

foreach ($lines as $line) {
    if (strpos($line, $specificString) !== false) {
        $found = true;
    }
    
    if (!$found) {
        fwrite($output, $line);
    }
}

fclose($output);