What are the best practices for implementing a search function in PHP that searches multiple lines of text in a file?

When implementing a search function in PHP that searches multiple lines of text in a file, it is important to read the file line by line and use regular expressions to match the search query. By using a loop to iterate through each line of the file, we can check if the search query is present in each line and return the results accordingly.

<?php
// Open the file for reading
$file = fopen('example.txt', 'r');

// Search query
$search_query = 'example';

// Loop through each line of the file
while (!feof($file)) {
    $line = fgets($file);
    
    // Use regular expression to match search query in each line
    if (preg_match("/$search_query/", $line)) {
        echo $line; // Output the line if search query is found
    }
}

// Close the file
fclose($file);
?>