使用PHP在文本文件中搜索短语/单词

6
我该如何使用PHP扫描目录以查找特定文本行并列出所有匹配的文件?
谢谢。
7个回答

7

我几天前实际上写了一个这个的函数...

这是扫描每个文件的基本函数...

foreach (glob("<directory>/*.txt") as $search) {
    $contents = file_get_contents($search);
    if (!strpos($contents, "text")) continue;
    $matches[] = $search;
}

虽然不是最先进的方法,但我的函数要长得多,但它也使用了我其他各种类的所有函数,这基本上就是它的功能。


1

这里是一个 PHP 中如何严格完成此操作的简单示例...

  1. 获取目录中所有文件/目录的列表。

  2. 检查每个文件/目录名称是否为文件

  3. 获取文件内容

  4. 使用字符串搜索函数查找我们要查找的字符串的匹配项。如果存在匹配项,则打印文件名

<?php
$path = 'c:\\some\\cool\\directory';
$findThisString = 'Cool Cheese';

$dir = dir($path);

// Get next file/dir name in directory
while (false !== ($file = $dir->read()))
{   
    if ($file != '.' && $file != '..')
    {
        // Is this entry a file or directory?
        if (is_file($path . '/' . $file))
        {
            // Its a file, yay! Lets get the file's contents
            $data = file_get_contents($path . '/' . $file);

            // Is the str in the data (case-insensitive search)
            if (stripos($data, $findThisString) !== false)
            {
                // sw00t! we have a match
            echo 'match found in ' . $file . "<br>\n";
            }
        }
    }
}

$dir->close();

?>

1
如果文件很大,每次将文件读入内存并搜索其内容是过度的。如果您拥有目录的读取权限,可以通过结合execegrep来确定针在哪个文件中。
php > exec("egrep -rl 'string of what I want to find' full-or-relative-directory", $output);
php > print_r($output);
Array
(
  [0] => full-or-relative-directory/foo/bar.xml
)
php > $contents = file_get_contents($output[0]);

1

另一种方法是读取php文件,将内容放入数组中,然后使用类似于preg_grep的东西。

如果文件数量可能非常大,则可以使用UNIX grep命令以及php exec

我个人会选择第二种解决方案。


0

首先,您可能希望使用glob获取感兴趣的文件列表(如果您想要多个扩展名,只需合并结果数组或使用this)。然后循环遍历结果,使用file_get_contents打开文件,并使用strpos检查字符串。


1
可以使用以下代码更轻松地进行多个扩展名的处理:glob('*.{ext1,ext2,ext3}', GLOB_BRACE) - user142162

0

我不会在这里放置我的推荐答案,因为已经有5个人发表了解决此问题的好答案,但我会推荐一个替代方案。

您考虑过使用 Lucene 搜索引擎的 PHP 实现吗? 最著名的是来自 Zend Framework。 最好的事情是,您不必使用框架来使用 Lucene 库(只需包括库基本文件 - 记得将 Zend Libraries 目录添加到 include 路径中)。

我自己没有使用过它,并且听到的评价也非常不一致。 我唯一能想到的就是它可能对于小型脚本或项目来说过于复杂。

Lucene Library 的详细概述可在 Zend Framework 参考指南中找到。


-1
$directory = "/var/www/application/store/"; //define the path
$files1 = scandir($directory); //scandir will scan the directory 
$c = count($files1); //this will count all the files in the directory
print $c; 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接