grep with -f like in PHP

前端 未结 2 1968
终归单人心
终归单人心 2021-01-12 07:09

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/funct

2条回答
  •  走了就别回头了
    2021-01-12 08:03

    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

提交回复
热议问题