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?

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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.