What are some best practices for efficiently searching and extracting specific lines from a text file in PHP?
When searching and extracting specific lines from a text file in PHP, it is best to read the file line by line and use regular expressions to match the desired lines. By using functions like fopen(), fgets(), and preg_match(), you can efficiently search for and extract the lines that meet your criteria.
$filename = 'example.txt';
$searchTerm = 'specific';
$handle = fopen($filename, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if (preg_match("/$searchTerm/", $line)) {
echo $line;
}
}
fclose($handle);
} else {
echo "Error opening the file.";
}