PHP Regular Expressions
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. Example 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 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 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);
Because the code reads in everything all at once, it’s about three times faster than the code, 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.
No comments:
Post a Comment