【问题标题】:How to grab all files which have a specific word in it如何抓取所有包含特定单词的文件
【发布时间】:2020-06-20 10:20:30
【问题描述】:

对于平面文件博客系统,我使用.txt 文件,其中存储了所有数据。 txt 文件如下所示:

id_123456 // 1st line is id line
sport     // 2nd line is category line
...

我需要的是一组具有特定类别名称的 txt 文件。 这是我到目前为止所拥有的:


$filterthis = 'club';
$filematches = [];

$blogfiles = glob($dir.'/*.txt'); // read all the blogfiles (txt files)

foreach($blogfiles as $file) { // loop through all te files
    $lines = file($file, FILE_IGNORE_NEW_LINES); // file in to an array
    $category = $lines[1]; // the category line

    if (in_array($category, $filterthis)) {
        $filematches[] = $file; // array with all the files which have category "club"??
    }

所以$filematches 应该包含所有包含“俱乐部”类别的文件,但我没有成功

【问题讨论】:

  • 您是否曾希望改用数据库?
  • if (in_array($category, $filterthis)) - 你认为这两个中的哪一个是数组?根据示例内容,第二行是类别(字符串),您正在寻找$filterthis(字符串) - 两者都不会是数组。也许if( $category==$filterthis ){/* add to output */}
  • 我知道这是错误的,但我怎样才能实现我想要的呢?
  • 为什么不将信息保存为 JSON?我用这种格式制作了一个视频游戏,所以我不必使用数据库。查看此链接以获取示例:stackoverflow.com/questions/2467945/…

标签: php arrays


【解决方案1】:

你的代码有错误

$filterthis = 'club';
$filematches = [];

$blogfiles = glob($dir.'/*.txt'); // read all the blogfiles (txt files)

foreach($blogfiles as $file) { // loop through all te files
    $lines = file($file, FILE_IGNORE_NEW_LINES); // file in to an array
    $category = $lines[1]; // the category line

    if (in_array($category, $filterthis)) {
        $filematches[] = $file; // array with all the files which have category "club"??
    }

$filterthis = 'club';

上面的变量“$filterthis”是一个String类型

$category = $lines[1]; // the category line

上面的变量“$category”也是字符串(当你从lines数组中取出整行时)

然后是你的情况

 if (in_array($category, $filterthis))

您正在使用 in_array 函数,该函数接受第一个参数作为针头,第二个参数接受一个数组,但您提供了字符串作为两个参数

在你的 if 条件下,改变条件

if($category == $filterthis)

然后就可以了

【讨论】:

  • "am not sure if you are able to read this kind of text, But to me it seems cool, So I just used it to show my profile description. That's all for now " '-)
  • 很遗憾,if($category == $filterthis) { $filtercategorymatches[] = $file; } 对我不起作用~
  • 您使用了 $buffer 变量进行比较,但我认为您应该使用 $category ?
  • 抱歉,$buffer 应该是 $category
  • 天哪,这是我的个人资料,我忘记了,@ProfessorAbronsius 很好,哈哈 :)
【解决方案2】:
foreach($blogfiles as $file) { // loop through all te files
    $lines = file($file, FILE_IGNORE_NEW_LINES); // file in to an array
    $category = $lines[1]; // the category line

    if(strpos(strtolower($category), $filterthis) !== FALSE) { // strtolower; category word not case sensitive
        $filematches[] = $file; // this gives you the desired array 
    }

【讨论】:

    猜你喜欢
    • 2013-10-15
    • 2017-02-17
    • 1970-01-01
    • 2020-05-11
    • 2011-08-29
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多