"Did you mean" search function

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
warren
Forum Newbie
Posts: 3
Joined: Mon Jun 06, 2005 7:34 am

"Did you mean" search function

Post by warren »

Hi there, I have a basic "Did you mean" function, which works, but there are a few problems.
1. If more than 1 word is queried, it will only reprint the correctly spelt word and ignore the misspelt word.
2. If all the words are misspelt it combines the words and comes up with 1 word.

I think it needs a metaphone function added to the levenshtein function.
Because users can type in a string of words, I need the function to loop through each word individually and come up with a

closest match for each word, and skip words that aren't mispelt. Although when it prints the new string it should also

include the words spelt correctly, so that the user can continue searching for the whole string.

Here is the code I have so far.

Code: Select all

-------------------------------
// input misspelled word
$input = $queryword;

// array of words to check against
$sql = "SELECT * FROM keywords";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
extract($row);
$words[] = $keyword;
}
		
// no shortest distance found, yet
$shortest = -1;

// loop through words to find the closest
foreach ($words as $word) {

// calculate the distance between the input word, and the current word
$leven = levenshtein($input, $word);

// check for an exact match
if ($leven == 0) {

// closest word is this one (exact match)
       $closest = $word;
       $shortest = 0;

// break out of the loop
       break;
   }

// if this distance is less than the next found shortest distance, OR if a next shortest word has not yet been found
   if ($leven <= $shortest || $shortest < 0) {
       // set the closest match, and shortest distance
       $closest  = $word;
	   $shortest = $leven;
   }
}
	print "<font color=\"#999999\">"."Did you mean "."<b><a 

href=\"?query=$closest&search=1\">"."$closest"."</a></font></b>";
	}
JCART | Please use

Code: Select all

tags when posting php code. Review [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color][/size]
Post Reply