Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep with -f like in PHP

Tags:

grep

php

Is there such a function in PHP that does grep -f filename in unix/linux systems. If there is none, what PHP functions/tools would help in creating a customised method/function for this. Thanks!

like image 484
JCm Avatar asked May 19 '12 08:05

JCm


2 Answers

Actually IMHO, I'd say it's the following:

$result = preg_grep($pattern, file($path));

See preg_grep­Docs and file­Docs.

If you need to do that (recursively) over a set of files, there is also glob and foreach or the (Recursive)DirectoryIterator or the GlobIterator­Docs and not to forget the RegexIterator­Docs.


Example with SplFileObject and RegexIterator:

$stream = new SplFileObject($file); 
$grepped = new RegexIterator($stream, $pattern); 

foreach ($grepped as $line) {
    echo $line;
}

Output (all lines of $file containing $pattern):

$grepped = new RegexIterator($stream, $pattern); 
foreach ($grepped as $line) {
    echo $line;
}

Demo: https://eval.in/208699

like image 183
hakre Avatar answered Oct 21 '22 02:10

hakre


You can combine the file_get_contens() function to open a file and the preg_match_all() function to capture contents using a regex.

$file = file_get_contents ('path/to/file.ext');
preg_match_all ('regex_pattern_here', $file, $matches);
print_r ($matches);
like image 45
Jeroen Avatar answered Oct 21 '22 04:10

Jeroen