【问题标题】:php scandir for given $q search query给定 $q 搜索查询的 php scandir
【发布时间】:2021-02-25 11:43:26
【问题描述】:

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

【问题讨论】:

  • 我发现你的概念相当有问题——在 PHP 中,scan-dir 是针对它的 INI 文件。你试过什么了?没有显示任何尝试,但它只是给了我-teh-codez。对不起,但我还没有愚蠢到做你的工作。请参阅slash7.com/2006/12/22/vampires ...发布您的规格不属于问题。

标签: php search scandir


【解决方案1】:

假设你有这个目录结构:

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;
    }
}

经过测试,可以解决问题。

【讨论】:

  • 您好,非常感谢您的回复和回答。我有不同名称的 .txt 文件,例如一些 word.txt 和其他 word.txt。我只想在 /mydir/ 目录中搜索 .txt 文件名,如果搜索查询与 .txt 文件名匹配,则包含 .txt 文件作为结果。这是一个带有 $q 变量的 php 搜索登录页面。我知道我想在这里做的事情有点棘手。:)
  • $search = $q.txt;以某种方式将搜索查询与 .txt 文件扩展名放在一起。:)
  • 好的@BizzyFizzy,我已经根据您的需要更新了我的答案。测试它有效。让我知道它是否适合您。
  • 太棒了!非常感谢您的解决方案@Monnmcjo!祝你有美好的一天!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-12
  • 2011-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-25
  • 2015-11-27
相关资源
最近更新 更多