Reputation: 1273
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?
Upvotes: 0
Views: 50
Reputation: 32262
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
}
}
Upvotes: 1