Jump to content

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


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);

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.