How to match one long string phrase against another in PHP?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sameerpanjwani
Forum Newbie
Posts: 1
Joined: Mon Sep 15, 2008 11:45 pm

How to match one long string phrase against another in PHP?

Post by sameerpanjwani »

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?
User avatar
Ziq
Forum Contributor
Posts: 194
Joined: Mon Aug 25, 2008 12:43 am
Location: Russia, Voronezh

Re: How to match one long string phrase against another in PHP?

Post by Ziq »

This is the simplest example:

Code: Select all

 
<?
$data = 'You have selected tea, biscuits and an ice-cream';
$search = array('tea', 'biscuits');
 
foreach ($search as $v) $data = str_ireplace($v, '<span style="background-color: yellow;">'.$v.'</span>', $data);
 
echo $data;
?>
 
Last edited by Ziq on Tue Sep 16, 2008 4:06 am, edited 2 times in total.
User avatar
Ziq
Forum Contributor
Posts: 194
Joined: Mon Aug 25, 2008 12:43 am
Location: Russia, Voronezh

Re: How to match one long string phrase against another in PHP?

Post by Ziq »

But i don't know... If you need to search changed words (ice-cream, ice-creamS and e.t.c) it's harder than it.
Post Reply