2016-11-20 44 views
0

现在它只是搜索一个文本文件,但我希望它搜索整个目录,但我不知道如何去做:/需要关于如何搜索字符串的多个文本文件的帮助

<?php 
$searchfor = "example"; 
$file = 'file.txt'; 
$contents = file_get_contents($file); 
$pattern = preg_quote($searchfor, '/'); 
$pattern = "/^.*$pattern.*\$/m"; 
if (preg_match_all($pattern, $contents, $matches)) { 
echo "<pre>Matches were found for $searchfor:\n"; 
echo implode("\n", $matches[0]); 
?> 

我不想仅仅搜索一个文件“file.txt”,而是希望它搜索整个文件目录以查找字符串。

谢谢。

回答

0

这应该工作:

<?php 
$searchfor = "example"; 
$dir = "."; 
$pattern = preg_quote($searchfor, '/'); 
$pattern = "/^.*$pattern.*\$/m"; 
$files = scandir($dir); 
foreach($files as $file) { 
    $contents = file_get_contents($file); 
    if (preg_match_all($pattern, $contents, $matches)) { 
     echo "<pre>Matches were found for $searchfor:\n"; 
     echo implode("\n", $matches[0]); 
    } 
} 
?> 
+0

当我跑了,我有一大堆的这些东西... http://prntscr.com/d9gv3p –

+0

你需要指定'$目录的目录路径'。我编写代码的方式是在脚本的当前目录中运行,因此它只查找脚本中的匹配项。 – varlogtim