Jump to content

How to match one long string phrase against another and highlight the result


sameerpanjwani

Recommended Posts

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: Tea, Coffee, Biscuits, Ice-cream, Chocolates, Fruits

 

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?

Would that be the most efficient way (exploding string 2 and then comparing it with each word in string 1) because string 2 can contain as many as 60-70 words and as much for string 1. Would it take a lot of processing time if the strings became that long?

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"

Like this?

 

$str1 = "The items available are \"Drinks - tea, coffee\", \"Snacks - Biscuits\", \"Dessert - Ice-cream\"";

//These are words that you want highlighted
$str2 = "Tea, Coffee, Biscuits, Ice-cream";

//Build the matches
$arr = explode(",", $str2);
$match = array();

foreach($arr as $highlight){
$match[] = "/{$highlight}/is";
}

echo preg_replace($match, "<span style='background-color:yellow;'>\\0</span>", $str1);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.