13.6. Finding All Lines in a File That Match a Pattern
Problem
You want to find all the lines in a file that match a pattern.
Solution
Read the file into an array and use preg_grep( )
.
Discussion
There are two ways to do this. Here’s the faster method:
$pattern = "/\bo'reilly\b/i"; // only O'Reilly books $ora_books = preg_grep($pattern, file('/path/to/your/file.txt'));
Use the file( )
command to automatically load each line of
the file into an array element and preg_grep( )
to
filter the bad lines out.
Here’s the more efficient method:
$fh = fopen('/path/to/your/file.txt', 'r') or die($php_errormsg); while (!feof($fh)) { $line = fgets($fh, 4096); if (preg_match($pattern, $line)) { $ora_books[ ] = $line; } } fclose($fh);
Since the first method reads in everything all at once, it’s about three times faster then the second way, which parses the file line by line but uses less memory. One downside, however, is that because the regular expression works only on one line at a time, the second method doesn’t find strings that span multiple lines.
See Also
Recipe 18.6 on reading files into strings;
documentation on preg_grep( )
at http://www.php.net/preg-grep.
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.