PHP – similar did you mean script – Part 1
Problem
A year back, i have been searching for the did you mean script on word searching, like in the google search. But, it seemed all were more complicated, and need the complete dictionary database. Then i skip the concept.
Last week, i needed that Did You Mean script for a project, again i did not get a correct script. After a long search, i have decided to go with the PHP function similar_text.
The Idea
It is a word search [DEMO]. There are some courses available in the database, i have to give suggestions if there is any spelling mistake / no result. In this case, we are going to suggest only the existing words in our database, then why going for a complete dictionary? Just we can compare words from the database and give suggestions. For my project, my idea is to show some suggestions if no results found. This helps me instead of Did You Mean script.
Here assume the $keyword is just one word (will come to more than 1 words in part 2)
The script
First understand the PHP function similar_text
Function similar_compare()
function similar_compare($keyword, $course)
{
$similar_rate = 0.0;
$course_words = explode(" ", $course);
foreach($course_words as $value)
{
similar_text(strtoupper($keyword), strtoupper($value), $p);
if($p > $similar_rate)
$similar_rate = $p;
} //foreach
return $similar_rate;
}
This function first separate the words in the $course string. Then compare each word with the $keyword and returns the maximum similar rate. Here we use strtoupper, because function similar_text is case sensitive. It is better to change both the words to upper/lower case.
$keyword is the word to be searched in the database. First simply search words using
select * from course where course_name LIKE '%$keyword%'
If there is no result then search for the similar text with the words in the database with every row.
<?php
$sql2 = "select * from course";
$rsd2 = mysql_query($sql2);
while($rs2 = mysql_fetch_array($rsd2))
{
$course = $rs2['course_name'];
$rate = similar_compare($keyword, $course);
if($rate > 70)
{
//just displaying the percentage and course name from database
echo "$rate - $course <br/>";
//change this according to your requirement - eg: echo '<a href="course details.php?course_id='.$rs2['course_id'].'">'.$course.'</a><br/>';
} //if
} //while
?>
Here, we take every row, compare it with keyword using
$rate = similar_compare($keyword, $course);
if the similar rate ($rate) is greater than 70 (change this 70 according to your need) then you can suggest the row (here I am displaying the similar rate and course name)
Feel and Try
Read Full Post | Make a Comment ( None so far )