I am a bit confused on how to go about doing a match of one string against another. This is what I want to achieve: String 1: You have selected tea, biscuits and an ice-cream. String 2: The items available are "Drinks - tea, coffee"; "Snacks - Biscuits", "Dessert - Ice-cream" I want to match "String 1" against "String 2" and return "String 1" with all the matching words highlighted in yellow. So in this case, "String 1" would return with "tea", "biscuits" and "ice-cream" highlighted in yellow. How would I go about this?
There might be some better way, but this is what I can think of: explode the second string, then do a preg_replace_all using this array elements, and string 1. Use span style="color:yellow">array element</span> to do the highlight. regards
explode() string 2 into an array and use a function to search for each word in string 1. Once that's performed, you can use another function to replace the matches with another code (HTML) that will be echoed with highlighted words (matches).
Ok I've made a mistake, string 2 is not necessarily in such an easy to decode format like mentioned above, it could be more like: String 2: The items available are "Drinks - tea, coffee"; "Snacks - Biscuits", "Dessert - Ice-cream"
How would I explode the string without the quotes surrounding them, if i use explode using space as a parameter, the quotes still remain
Here you go! //Your first string, that will be checked for matches. $string1 = 'I hate your cat. Do you hate it?'; //The possible words that will be matched. $string2 = '"hate,"cat",it"'; //This removes the " ". $string2 = str_replace('"','',$string2); //Function to store the replacements. function text($obj) { $string1 = $obj; return $string1; } // $expo = explode(',',$string2); $howmany = count($expo); $i = 0; while($i <= $howmany) { $result = str_replace($expo[$i],'<span style="background-color:yellow;">'.$expo[$i].'</span>',$string1); $string1 = text($result); $i++; } //Results! print $result; Code (markup):