Recipe 22.5. Finding All Lines in a File That Match a Pattern

22.5.1. Problem

You want to find all the lines in a file that match a pattern.

22.5.2. Solution

Read the file into an array and use preg_grep( ).

22.5.3. Discussion

There are two ways to do this. Example 22-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 non-matching lines.

Quickly finding lines that match a pattern

$pattern = "/\bo'reilly\b/i"; // only O'Reilly books $ora_books = preg_grep($pattern, file('/path/to/your/file.txt'));

Example 22-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.

Efficiently finding lines that match a pattern

$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);

Since the code in Example 22-9 reads in everything all at once, it's about three times faster than the code in Example 22-10, which parses the file line by line but uses less memory. Keep in mind that since both methods operate on individual lines of the file, they can't successfully use patterns that match text that spans multiple lines.

22.5.4. See Also

Recipe 23.5 on reading files into strings; documentation on preg_grep( ) at

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: