用php搜索文本文件中的短语/单词
如何扫描目录中的特定文本行,并使用php列出所有匹配的文件用php搜索文本文件中的短语/单词,php,search,full-text-search,directory,Php,Search,Full Text Search,Directory,如何扫描目录中的特定文本行,并使用php列出所有匹配的文件 谢谢。首先,您可能希望获得感兴趣的文件列表(如果您需要多个扩展名,只需合并结果数组或使用)。然后循环遍历结果,用打开文件并用检查字符串 另一种方法是读取php文件,将内容放入数组,然后使用类似的方法 如果文件数量可能非常大,您可能希望将UNIXgrep命令与php一起使用 我个人会选择第二种解决方案。几天前我实际上为此编写了一个函数 下面是扫描每个文件的基本函数 foreach (glob("<directory>/*.tx
谢谢。首先,您可能希望获得感兴趣的文件列表(如果您需要多个扩展名,只需合并结果数组或使用)。然后循环遍历结果,用打开文件并用检查字符串 另一种方法是读取php文件,将内容放入数组,然后使用类似的方法 如果文件数量可能非常大,您可能希望将UNIXgrep命令与php一起使用
我个人会选择第二种解决方案。几天前我实际上为此编写了一个函数 下面是扫描每个文件的基本函数
foreach (glob("<directory>/*.txt") as $search) {
$contents = file_get_contents($search);
if (!strpos($contents, "text")) continue;
$matches[] = $search;
}
foreach(glob(“/*.txt”)作为$search){
$contents=file\u get\u contents($search);
如果(!strpos($contents,“text”))继续;
$matches[]=$search;
}
这不是最先进的方法,我的函数要长得多,但它也使用了我的各种其他类中的所有函数,这基本上就是它所做的。下面是一个简单的例子,说明了如何严格地用php实现这一点
我不会把我推荐的答案放在这里,因为有5个人已经发布了关于如何解决这个问题的好答案,但我会推荐一个替代方案
您是否考虑过使用Lucene搜索引擎的PHP实现?最值得注意的是来自美国。最好的情况是,您不必使用框架来使用Lucene库(只需包含库基文件,记住将Zend Libraries目录添加到include路径)
我自己也没有用过,听到的评论也很复杂。我唯一能想到的是,对于一个小脚本或项目来说,它可能太复杂了
Zend Framework参考指南中有一个非常详细的内容。如果文件很大,那么必须将每个文件读入内存,然后搜索其内容,这是一种过分的做法
如果您对该目录具有读取权限,则可以通过结合以下内容来确定指针所在的文件:
使用:glob('*.{ext1,ext2,ext3}',glob_括号)可以更轻松地完成多个扩展。
<?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();
?>
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]);
$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;