使用 -f 的 grep 就像在 PHP 中一样

2022-01-06 00:00:00 php grep

PHP 中是否有这样的函数在 unix/linux 系统中执行 grep -f filename.如果没有,什么 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!

推荐答案

实际上恕我直言,我想说的是以下内容:

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

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

参见preg_grep­文档file­文档.

如果您需要对一组文件(递归地)执行此操作,还有 globforeach 或 (Recursive)DirectoryIteratorGlobIterator­Docs 并且不要忘记 RegexIterator­文档.

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.

SplFileObject 和 RegexIterator 的示例:

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

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

输出(所有包含 $pattern 的 $file 行):

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

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

演示:https://eval.in/208699

相关文章