简体   繁体   English

在PHP中的多个TXT文件中查找特定文本

[英]Find specific text in multiple TXT files in PHP

I want to find a specific text string in one or more text files in a directory, but I don't know how. 我想在目录中的一个或多个文本文件中找到特定的文本字符串,但我不知道如何。 I have Googled quite a long time now and I haven't found anything. 我已经在Google上搜索了很长一段时间,但没有找到任何东西。 Therefor I'm asking you guys how I can fix this? 因此,我问你们我该如何解决?

Thanks in advance. 提前致谢。

If it is a Unix host you're running on, you can make a system call to grep in the directory: 如果它是您正在运行的Unix主机,则可以在目录中对grep进行系统调用:

$search_pattern = "text to find";
$output = array();
$result = exec("/path/to/grep -l " . escapeshellarg($search_pattern) . " /path/to/directory/*", $output);

print_r($output);
// Prints a list of filenames containing the pattern

You can get what you need without the use of grep. 您无需使用grep即可获得所需的内容。 Grep is a handy tool for when you are on the commandline but you can do what you need with just a bit of PHP code. Grep是在命令行时使用的便捷工具,但是您只需使用少量PHP代码就可以完成所需的工作。

This little snippet for example, gives you results similar to grep: 例如,以下小片段将为您提供类似于grep的结果:

$path_to_check = '';
$needle = 'match';

foreach(glob($path_to_check . '*.txt') as $filename)
{
  foreach(file($filename) as $fli=>$fl)
  {
    if(strpos($fl, $needle)!==false)
    {
      echo $filename . ' on line ' . ($fli+1) . ': ' . $fl;
    }
  }
}

If you're on a linux box, you can grep instead of using PHP. 如果您使用的是Linux系统,则可以使用grep代替使用PHP。 For php specifically, you can iterate over the files in a directory , open each as a string , find the string , and save the file if the string exists. 专门针对php,您可以遍历目录中的文件,将 每个文件作为字符串打开找到该字符串 ,然后保存该文件(如果该字符串存在)。

Just specify a file name, get the contents of the file, and do regex matching against the file contents. 只需指定一个文件名,获取文件的内容,然后对文件内容进行正则表达式匹配即可。 See this and this for further details regarding my code sample below: 对以下方面我的代码示例的详细信息:

    $fileName = '/path/to/file.txt';
    $fileContents = file_get_contents($fileName);
    $searchStr = 'I want to find this exact string in the file contents';

    if ($fileContents) {  // file was retrieved successfully

        // do the regex matching
        $matchCount = preg_match_all($searchStr, $fileContents, $matches);

        if ($matchCount) {  // there were matches
            // $match[0] will contain the entire string that was matched
            // $matches[1..n] will contain the match substrings    
        }

    } else {  // file retrieval had problems

    }

Note: This will work irrespective of whether or not you're on a linux box. 注意:无论您是否在linux机器上,这都将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM