Forum Moderators: coopster
For instance, if my string to find is 'make the pie higher', I want to be able to match this in text of 'higher the pie make' (I think I'm starting to sound like yoda here ;))
The only way my somewhat less than perfect PHP coding mind can think of to make this work is:
- count the number of words to find
- match them one by one
- check there were the same number of matches as the number of words
While this works, it strikes me as an ugly and inefficient way of doing things - does anyone have any better suggestions?
Here's a shot at it...
$myString1 = 'make the pie higher';
$myString2 = 'higher the pie make';
//Get the words into arrays
$myWords1 = explode(" ", $myString1);
$myWords2 = explode(" ", $myString2);
//Sort each array to match up words
sort($myWords1);
sort($myWords2);
//Compute differences in arrays with index checking
$result = array_diff_assoc($myWords1,$myWords2);
//If an array is returned then something is not matching
if(empty($result)) {
echo "match";
} else {
echo "fail";
I'm using array_diff_assoc to catch any double words like 'higher higher the pie make'. If you're not interested in this then just leave out the sort functions and use array_diff.
Tim
Unfortunately, I wasn't asking for the right thing ;)
I wanted to match the occurance of all the words of 'make the pie higher' in a string of many words. I've ended up with a variation of my original code:
$pastry="mmmm, the pie higher I want to make";
$pie="make the pie higher";
$count = count(explode(" ", $pie));
$piearray = explode(" ", trim($pie));
foreach ($piearray as $value) {
if (preg_match("/\b".$value."\b/im", $pastry))
{$found=$found+1;}
}
if ($found==$count ) {
// the pie is higher
}
else {
// no pie for me
}
I'm not sure if this is an efficient approach or not (any comments?).
Anyway, is there any reason why you're using preg_match? This little tip is from the manual [php.net]
Tip: Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster.
Tim