如何使用 php 搜索特定行的 txt 文件

How to search in particular lines of txt file with php

我将文章中的数据存储在 .txt 文件中。 txt 文件如下所示:

id_20201010120010                           // id of article
Sport                                       // category of article
data/uploads/image-1602324010_resized.jpg   // image of article
Champions League                          // title of article
Nunc porttitor ut augue sit amet maximus... // content of the article 
2020-10-10 12:00                            // date article 
John                                        // author of article
oPXWlZp+op7B0+/v5Y9khQ==                    // encrypted email of author
football,soccer                             // tags of article
true                                        // boolean (SHOULD BE IGNORED WHEN SEARCHING)
false                                       // boolean (SHOULD BE IGNORED WHEN SEARCHING)

要在文章中搜索,请使用以下代码:

$searchthis = strtolower('Nunc');
$searchmatches = [];
    
foreach($articles as $article) { // Loop through all the articles
    $handle = @fopen($article, "r");
    if ($handle) {
        while (!feof($handle)) {
            $buffer = fgets($handle);
            if(strpos(strtolower($buffer), $searchthis) !== FALSE) { // strtolower; search word not case sensitive
                $searchmatches[] = $article; // array of articles with search matches                   
            }
            
        }
        fclose($handle);
    }
}

//show results:
if(empty($searchmatches)) { // if empty array
    echo 'no match found';
}
print_r($searchmatches);

一切正常!但是当搜索像 true 这样的词时,他找到了几乎所有文章,因为在所有文章中最后一行都是 2 个布尔值。那么如何跳过 txt 文件的最后两行进行搜索呢?

一种方法是使用 file to read the entire file into an array, then array_slice to strip the last two elements from the array. You can then iterate through the array looking for the search value. Note you can use stripos 进行不区分大小写的搜索:

foreach ($articles as $article) {
    $data = file($article);
    if ($data === false) continue;
    $data = array_slice($data, 0, -2);
    $search = 'league';
    foreach ($data as $value) {
        if (stripos($value, $search) !== false) {
            $searchmatches[] = $article;
        }
    }
}

要读取您的文件,而不是使用 fopenfgets 等,就像一些 C 代码一样,只需使用 file() 函数。它将读取所有文件并将其放入一个行数组中。然后 select 您要搜索的行。

<?php

$article = file('article-20201010120010.txt');

// Access each information of the article you need directly.
$id       = $article[0];
$category = $article[1];
// etc...

// Or do it like this with the list() operator of PHP:
list($id, $category, $image, $title, $content, $date, $author, $email_encrypted, $tags, $option_1, $option_2) = $article;

// Now do the insensitive seach in the desired fields.
$search = 'porttitor'; // or whatever typed.

if (($pos = stripos($content, $search)) !== false) {
    print "Found $search at position $pos\n";
} else {
    print "$search not found!\n";
}