需要有关如何在字符串中搜索多个文本文件的帮助

时间:2016-11-20 03:27:59

标签: php

现在它只搜索一个文本文件,但我希望它搜索整个目录,但我不知道如何去做:/

<?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”,而是希望它搜索整个文件目录以查找字符串。

谢谢。

1 个答案:

答案 0 :(得分: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]);
    }
}
?>