65.9K
CodeProject 正在变化。 阅读更多。
Home

搜索听起来像...的词

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.33/5 (2投票s)

2008年6月28日

CPOL
viewsIcon

18570

结合方法,更好地搜索在MySQL数据库中听起来像其他词的词。

引言

PHP函数similar_text和其他变体在寻找相似词时很有用。与MySQL结合使用时,需要额外的编程。 MySQL函数soundex是不够的。

背景

最近,我需要查询一个数据库并将返回的结果与搜索词进行比较。如果表中的字段包含一个词,这将很容易,但被搜索的字段包含许多词作为名称的一部分,通常由空格分隔,有时也用逗号分隔。

使用代码

这个简短的代码片段包含将数据库返回的结果标记化的主要部分,并使用similar_text函数比较每个术语。 该代码需要扩展才能一次搜索多个词。

$trimmed = "word_to_search"; // we only search for one word

$dblink = mysql_connect("localhost", "%user%", "%password%")  
 or die("connection was unsuccessful");
mysql_select_db("db_name", $dblink) 
 or die("MYSQL Database Error: " . mysql_error());

//We're only selecting one field 
$query = mysql_query("SELECT field_name FROM TABLE");

while($r = mysql_fetch_array($query))
{
    //parse the multi-word string returned
    $tok = strtok($r["field_name"], ", ");
    while($tok !== false)
    {
        //needed to strip a quote character that enclosed the string inside the field 
        similar_text(strtoupper($trimmed), trim(strtoupper($tok),'"'), $percentage);
        $percentage = number_format($percentage, 0);
        if($percentage >= 80) //define a threshold, in this case an 80 percent match
        {
            //prints the results to clearly indicated which terms meet the threshold
            $results_record["matched on:<font color=\"#ff0000\"> " .
              trim(strtoupper($tok),'"') . 
              "</font> in string: <font color=\"#0000CC\"> " . 
              $r[field_name] . "</font>"]  = $percentage;
        }
        $tok = strtok(", ");
    } 
}

if (!$results_record)
{
    echo "nothing found";
}
else
{
    asort($results_record, SORT_NUMERIC);
    //echo key pair values
    foreach($results_record as $result => $percentage)
    {
        echo $result . " - " . $percentage."%<BR>" ;
    }
}
© . All rights reserved.