I'm implementing a "Tags" feature in our custom product management system. Each product has a comma seperated list of tags associated. We have a "tag search" with check boxes. The user can check multiple tags and it will filter with ajax with all the selected tags, so all tags need to be matched together. Example.
Tags: Tag1,Tag2,Tag3
#1-product-tags: Tag3,Tag10,Tag2
#2-product-tags: Tag1,Tag3,Tag10
#3-product-tags: Tag5,Tag1,Tag3
#4-product-tags: Tag8,Tag4,Tag20
#5-product-tags: Tag20,Tag100,Tag500
When filtering with the above tags checked, I expect to return #1,#2,#3 only because the given tags are listed in the product-tags column of these products.
Im currently trying to use regular expressions by dynamically creating a regex when the user checks the tags. In order to qualify as a match, the product must have all tags checked. Im generating this like so:
<?php
//empty collection array to fill with product loop
$collection = array();
//dynamically generated regex
$regex = "\b" . $tag1 . "|" . $tag2 . "|" . $tag3 . "\b/i";
//loop through each product and throw matches to collection
foreach($products as $product) {
if(preg_match($regex,$product->tags)) {
array_push($collection,$product);
}
}
?>
I am not getting the expected result doing it this way. What is the best way I can get my expected result. Im not too great with Regular Expressions but I am learning.