我有下面的PHP脚本,我希望它在目录中所有文件内搜索一个字符串,并向我显示包含该字符串的文件。
但是现在它显示了我所有的文件。
<?php
$dir = "../scanner";
// Sort in ascending order
$a = array_diff( scandir("$dir"), array(".", "..") );
foreach ( $a as $file)
//script die de files gaat scannen
{
$searchthis = "eval";
$matches = array($file);
//door zoekt het opgegeven bestand of er een string met eval in staat
$handle = @fopen('C:\Users\Collin\PhpstormProjects\wordpress\\' . $file, "r");
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
if(strpos($buffer, $searchthis) !== FALSE)
$matches[] = $buffer;
}
fclose($handle);
}
//weergeef resultaten
print_r($matches);
}
?>
答案 0 :(得分:0)
您始终在循环内设置和打印$matches
数组。因此,将其中一些代码移出循环...
$matches = array(); // Move this here and set to blank
foreach ( $a as $file)
//script die de files gaat scannen
{
$searchthis = "eval";
//...
}
print_r($matches); // Move this after the end of the loop
然后您可能想要添加到匹配记录中...
$matches[] = $buffer;
您可以将其设置为文件...
$matches[$file] = $buffer;
或添加[]
制成匹配项列表
$matches[$file][] = $buffer;
或者保持行数,以便也可以添加它。
答案 1 :(得分:0)
我不确定我能100%给您。但是这行似乎没用$matches = array($file);
以下是我认为可以为您提供帮助的内容:
foreach ( $a as $file)
//script die de files gaat scannen
{
$searchthis = "eval";
//door zoekt het opgegeven bestand of er een string met eval in staat
$handle = @fopen('C:\Users\Collin\PhpstormProjects\wordpress\\' . $file, "r");
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
if(strpos($buffer, $searchthis) !== FALSE)
$matches[] = $file;
break;
}
fclose($handle);
}
}
//weergeef resultaten
print_r($matches);