You want to find all the lines in a file that match a pattern.
Read the file into an array and use preg_grep().
There are two ways to do this. Example 23-9 is faster, but uses more memory. It uses the file() function to put each line of the file into an array and preg_grep() to filter out the nonmatching lines.
Example 23-9. Quickly finding lines that match a pattern
1 2 |
$pattern = "/\bo'reilly\b/i"; // only O'Reilly books $ora_books = preg_grep($pattern, file('/path/to/your/file.txt')); |
Example 23-10 is slower, but more memory efficient. It reads the file a line at a time and uses preg_match() to check each line after it’s read.
Example 23-10. Efficiently finding lines that match a pattern
1 2 3 4 5 6 |
$fh = fopen('/path/to/your/file.txt', 'r') or die($php_errormsg); while (!feof($fh)) { $line = fgets($fh); if (preg_match($pattern, $line)) { $ora_books[ ] = $line; } } fclose($fh); |
Because the code in Example 23-9 reads in everything all at once, it’s about three times faster than the code in Example 23-10, which parses the file line by line but uses less memory.
Keep in mind that because both methods operate on individual lines of the file, they can’t successfully use patterns that match text that spans multiple lines.