O'Reilly logo

PHP Cookbook by Adam Trachtenberg, David Sklar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required