Question

I am trying to implement search function in my web application, what I am trying to do is search for a word in database and if it does not exist system should tell me or find me the closest match to the word. I implement code that search in data base and give me result but some times don't correct result when i try to implement another code i implement array give me the best result . I want to find the closest match to the word i search about it in array if word i search for it have some of Characters of the word in array tell me if this word i mean ? but in database has be arrangement in letters . i want solve this problem in database to give me result as array this is my index.php

<html>
<body>
<form method="post" action="me.php">
Search :  =<input type="text" name="name" id="x" autocomplete="off">
<input type="submit" name="submit" id="submit" value="Search">
</form>
</html>

and this is my database code me.php

<?php

        $input = $_POST['name'];
        if( mysql_connect("localhost" , "root" , "") &&
            mysql_select_db("test") )
        {
            echo 'connected<br>';
        }
        else
        {
            echo 'Failed';
        }

        if( $query_run = mysql_query("SELECT * FROM `table` WHERE `mytext` LIKE '%$input%'") )
        {
            if(mysql_num_rows($query_run) > 0)
            {
                while( $result = mysql_fetch_assoc($query_run) )
                {
                    $sender = $result['id'] ;
                    $message = $result['mytext'] ;

                    echo "<br>      &nbsp;&nbsp;&nbsp;&nbsp; From: $sender:&nbsp;
                             $message<br>";
                }
            }
            else
            {
                echo 'Bad KeyWord';
            }

        }
        else
        {
            return false ;
        }
?>

and this is my array code two.php

<?php

$input = $_POST["name"];
$words  = array('apple','pineapple','banana','orange',
                'radish','anything','carrot','pea','bean','potato');
$shortest = -1;
foreach ($words as $word) {
    if ($input == $word) {
        $closest = $word;
        $shortest = 0;
        break;
    }
    $lev = levenshtein($input, $word);
    if ($lev <= $shortest || $shortest < 0) {
        $closest  = $word;
        $shortest = $lev;
    }
}
echo "Input word: $input\n";
if ($shortest == 0) {
    echo "Exact match found: $closest\n";
} else {
    echo "Did you mean: $closest?\n";
}
?>

please help me to solve this problem

Was it helpful?

Solution

Check this Levenshtein distance you can find implementation that can help you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top