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



我将文章中的数据存储在.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将整个文件读取到数组中,然后使用array_slice从数组中剥离最后两个元素。然后,您可以在数组中进行迭代,以查找搜索值。注意,您可以使用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;
}
}
}

要读取文件,不要像使用某些C代码那样使用fopenfgets等,只需使用file()函数即可。它将读取所有文件,并将其放入一个行数组中。然后选择要进行搜索的行。

<?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 $posn";
} else {
print "$search not found!n";
}

最新更新