0

For a flatfile blog system, i store all the data in a .txt file. On line 7 of the txt file , there are tags stored, comma separated like below:

id_12345678     // 1st line; id line
club            // 2nd line; category line
...
sport,athletics // 7th line; tag line

To grab all the files which have a specific tag, e.g sport and find the corresponding file in which that tag is founded, i use this code:

$search_tag = 'sport'; 
$blogfiles = glob($dir.'/*.txt'); // read all the blogfiles
$tag_matches = array();

foreach($blogfiles as $file) { // Loop through all the blogfiles
        $lines = file($file, FILE_IGNORE_NEW_LINES); // file into an array
        $buffer = $lines[7]; // the tag line

        if(strpos(strtolower($buffer), $search_tag) !== FALSE) { // strtolower; tag word not case sensitive                                         
                $tag_matches[] = $file; // array of files which have the specific tag inside                                                            
        }
    }

This works fine! $tag_matches gives me an array of files which contain the tag sport.

Now i want to search on multiple tags, per example sport,athletics. What i need to achieve now is an array of all the files which contain at least one of these tags.

So i tried:

$search_tag = array('sport','athletics'); 
...
if(strpos(strtolower($buffer), $search_tag) !== FALSE) { // $search_tag as array of multiple tags  does not work anymore ???                                        
                $tag_matches[] = $file; // array of files which have the specific tag inside                                                            
        }

How do i have to do this?

1 Answer 1

1

Your current solution will match anything where the search string is even a portion of a tag. Eg: Do a tag search for e and you'll match just about every article.

Split the tags properly and do full matching:

$buffer = 'foo,bar,baz';
$tags = explode(',', $buffer);

$search_tags = ['bonk', 'bar'];

$tag_matches = [];
foreach($search_tags as $tag) {
    if( in_array($tag, $search_tags) ) {
        $tag_matches[] = 'yes'; // article id here
        break; // you only need one match
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.