What is the best approach to output not only the first line but also the following 4 lines after a specific string is found in PHP?

To output not only the first line but also the following 4 lines after a specific string is found in PHP, you can read the file line by line and keep track of whether the specific string has been found. Once the string is found, you can output the current line and the next 4 lines. You can achieve this by using a flag to indicate when the specific string is found and incrementing a counter to output the next 4 lines.

<?php
$filename = 'example.txt';
$searchString = 'specific string';
$linesAfter = 4;

$handle = fopen($filename, "r");
$found = false;
$counter = 0;

while (($line = fgets($handle)) !== false) {
    if (strpos($line, $searchString) !== false) {
        $found = true;
        echo $line;
        $counter = $linesAfter;
    } elseif ($found && $counter > 0) {
        echo $line;
        $counter--;
        if ($counter === 0) {
            break;
        }
    }
}

fclose($handle);
?>