【问题标题】:Get the name of the file that contains a string [closed]获取包含字符串的文件的名称[关闭]
【发布时间】:2014-10-20 19:43:06
【问题描述】:

我想获取包含字符串的文件的文件名(在特定文件夹中)。

例如:有一个名为“test”的文件夹。在这个文件夹中有三个文件,但其中只有一个包含字符串“hello”。现在我想用 PHP 取回这个文件的名称。

(所有文件都是.txt)

提前致谢!

【问题讨论】:

  • 你必须打开并阅读所有文件..
  • 哎哟。在 PHP 中,这将是一项计算成本很高的事情。
  • this via console : grep -nr "your string 123456" Folder ,告诉你位于哪一行,也在那个文件中
  • 只需 glob 文件夹,获取文件,在其中执行 strpos,成功返回文件名。

标签: php regex file file-get-contents


【解决方案1】:
  1. 扫描文件夹。
  2. 打开每个文件/读取内容。
  3. 使用函数stristr检查字符串“hello”是否存在。

【讨论】:

  • 现在您正在打开每个文件...这在 PHP 中需要很长时间
  • 至少这是一个真正的跨平台解决方案
  • @RichardBernards 三个文本文件打开时间不会太长。
【解决方案2】:

假设是 *nix 环境

以下将产生一个$output 变量,其中包含一个带有文件名的数组:

$output = exec("grep -l 'hello' test/*.txt");

【讨论】:

  • 你假设他正在使用 *nix 环境..
  • 只要 exec() 可用,这是一个很好的解决方案。
  • @LorenzoMarcon 我已经用你的有用评论更新了我的答案
  • this 用于搜索多个字符串:grep -nr "your string 123456" 文件夹,在所有文件和所有子目录中
【解决方案3】:
  1. 获取文件夹中给定扩展名的所有文件名。
  2. 按顺序读取所有文件的内容。
  3. 读取每个文件的每一行并查找匹配“hello world”的单词
  4. 将包含匹配项的文件名保存在数组中。

尚未对其进行测试,但应该可以使用以下方法:

$data = glob(FOLDER . "*.txt");

// filter
$filter = array();

// read contents of all files
for($i=0; $i<count($data); $i++) {
    $file_path = $data[$i];

    // open file in read-only mode
    $fp = fopen( $file, 'r' );

    // read file data
    $file_data = fread($fp, filesize($file_path));

    // close file handle
    fclose($fp);

    // make sure we catch CR-only line endings.
    $file_data = str_replace("\r", "\n", $file_data);

    // match using regexp
    if(preg_match('/(hello world)/im', $file_data)) {
        $file_name = basename($data[$i]);
        array_push($filter, $file_name);
    }
}

// output filtered file names
echo nl2br(print_r($filter, TRUE));

【讨论】:

    猜你喜欢
    • 2012-07-04
    • 2017-08-16
    • 1970-01-01
    • 2018-05-09
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    相关资源
    最近更新 更多