phparraysfilesearchfeof

How to search in particular lines of txt file with php


I store data from an article in a .txt file. A txt file looks like this:

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)

For searching in articles, is use this code below:

$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);

This works all fine! But when searching on a word like true, he finds almost all articles because in all articles are the 2 booleans at the last lines. So how can i skip these 2 last lines of the txt file from searching?


Solution

  • One way to do this would be to use 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 to do a case-insensitive search:

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