给定 $q 搜索查询的 php scandir

问题描述

我在 /mydir/ 目录中有搜索值,如“搜索值”(定义为 $q)和名为“搜索值.txt”的 .txt 文件。我如何 scandir /mydir/ 查找搜索值 ($q) 并将找到的 .txt 文件PHP include 命令放入页面?或者是将 $q 值放入 PHP file_get_contents PHP 代码的更好方法(我的意思是将它们像 txt 文件名一样放在一起 (q$.txt - searchvalue.txt 不知何故) 并将 .txt 文件内容拉入页面?如果是,如何?提前致谢。

解决方法

假设你有这样的目录结构:

mydir
  --file1.tx
  --file2.tx
index.php

index.php

$filepath = glob("mydir/*.txt");//read all txt files in data directory
//print_r($filepath);//debug purpose
$search = 'file1';

// Browse all files and search the $search string in filenames
foreach ($filepath as $filename) {

    // Give us file name only without the extension
    $fileNameOnly = basename($filename,'.txt');

    // Check if a file name only contains exactly our keyword $search
    $isExactMatch = preg_match("/\b".$search."\b/iu",$fileNameOnly);

    if ( $isExactMatch ) {
      // Include the .txt file as result
      require $filename;
    }
}

经过测试,确实有效。