&引用;你的意思是“什么?”;php和mysql的特性

&引用;你的意思是“什么?”;php和mysql的特性,php,mysql,search,Php,Mysql,Search,我已经在一个网站上创建了一个搜索功能,我想添加一个类型更正功能。 当我添加这些代码时,输出总是第一个“words”数组,请帮助 这是我的代码: <?php $input = $q; // array of words to check against $sql = "SELECT `English` FROM `dict`"; $result = mysql_query($sql); $words = mysql_fetch_array($result, MYSQL_BOTH); $s

我已经在一个网站上创建了一个搜索功能,我想添加一个类型更正功能。 当我添加这些代码时,输出总是第一个“words”数组,请帮助

这是我的代码:

<?php
$input = $q;

// array of words to check against
$sql = "SELECT `English` FROM `dict`";
$result = mysql_query($sql);
$words = mysql_fetch_array($result, MYSQL_BOTH);

$shortest=100;
// loop through words to find the closest
foreach ($words as $word) {

    // calculate the distance between the input word and the current word
    $lev = levenshtein($input, $word);
    //if the distance is shorter than the last shortest one, replace it.
    if ($lev <= $shortest) {
        // set the closest match, and shortest distance
        $closest  = $word;
        $shortest = $lev;
    }
}

echo "Input word: ".$input."<br />";
echo "Did you mean: ".$closest."?<br />";
?>

在MySQL中添加levenshtein函数

DELIMITER $$
CREATE FUNCTION levenshtein( s1 VARCHAR(255), s2 VARCHAR(255) )
RETURNS INT
DETERMINISTIC
BEGIN
DECLARE s1_len, s2_len, i, j, c, c_temp, cost INT;
DECLARE s1_char CHAR;
-- max strlen=255
DECLARE cv0, cv1 VARBINARY(256);
SET s1_len = CHAR_LENGTH(s1), s2_len = CHAR_LENGTH(s2), cv1 = 0x00, j = 1, i = 1, c = 0;
IF s1 = s2 THEN
RETURN 0;
ELSEIF s1_len = 0 THEN
RETURN s2_len;
ELSEIF s2_len = 0 THEN
RETURN s1_len;
ELSE
WHILE j <= s2_len DO
SET cv1 = CONCAT(cv1, UNHEX(HEX(j))), j = j + 1;
END WHILE;
WHILE i <= s1_len DO
SET s1_char = SUBSTRING(s1, i, 1), c = i, cv0 = UNHEX(HEX(i)), j = 1;
WHILE j <= s2_len DO
SET c = c + 1;
IF s1_char = SUBSTRING(s2, j, 1) THEN
SET cost = 0; ELSE SET cost = 1;
END IF;
SET c_temp = CONV(HEX(SUBSTRING(cv1, j, 1)), 16, 10) + cost;
IF c > c_temp THEN SET c = c_temp; END IF;
SET c_temp = CONV(HEX(SUBSTRING(cv1, j+1, 1)), 16, 10) + 1;
IF c > c_temp THEN
SET c = c_temp;
END IF;
SET cv0 = CONCAT(cv0, UNHEX(HEX(c))), j = j + 1;
END WHILE;
SET cv1 = cv0, i = i + 1;
END WHILE;
END IF;
RETURN c;
END$$
DELIMITER ;
根据您的问题和字典表,您可以使用此SQL命令

SELECT `English` FROM `dict` 
ORDER BY
 levenshtein(`English`, 'USER_INPUT')
 ASC LIMIT YOUR_LIMIT(Number of suggestions you want)

注意:-您应该对用户输入进行过滤,以防止SQL注入并删除特殊字符(这将提高速度并防止与注入相关的问题)

下面的示例中,当levenshtein函数和echo使用时,我将变量从数组的用法更改为字符串

    <?php

         // db connection parameter
        require $_SERVER['DOCUMENT_ROOT'] . "/php/db-params.php";

        $stmt = $pdo->query( "SELECT name FROM cities500 LIMIT 1999" );
        $words = $stmt->fetchAll( PDO::FETCH_ASSOC );
        $input = "nevyork";
        $shortest = 100;

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

            // calculate the distance between the input word and the current word
            $lev = levenshtein( $input, $word["name"] );
            //if the distance is shorter than the last shortest one, replace it.
            if ( $lev <= $shortest ) {
                // set the closest match, and shortest distance
                $closest  = $word;
                $shortest = $lev;
            };
        };

        echo "Input word: ".$input."<br />";
        echo "Did you mean: ".$closest["name"]."?<br />";

    //};
?>

我也有同样的问题,我决定编写自定义的简单函数来实现这一点。就我而言,这很好:

<?php 
$input = 'inputWord';

$statement = $connection->prepare("SELECT name FROM `words`");
$statement->execute(array());
$rows = $statement->fetchAll();
$resultArray = [];

foreach ($rows as $row) {
    $compSum = 0;
    for ($i = 0; $i < strlen($row[0]) - 1; $i++) {
        $searchPosition = strpos($input, $row[0][$i] . $row[0][$i + 1]);
        if (is_numeric($searchPosition)) {
            $compSum += abs($searchPosition - $i);
        } else {
            $compSum += 10;
        }
    }
    $lenDiference = strlen($input) - strlen($row[0]);
    if ($lenDiference > 0) {
        $compSum += $lenDiference * 10;
    }
    $resultArray[] = array('word' => $row[0], 'compSum' => $compSum);
}

function sortBySum($a, $b) {
    return $b['compSum'] - $a['compSum'];
}

usort($resultArray, 'sortBySum');
$bestMatch = array_pop($resultArray);

echo 'Input word: ' . $input . '<br/>';
if ($bestMatch['compSum'] < 50) {
    echo 'Did you mean: ' . array_pop($resultArray)['word'];
}

您是否使用不同的示例进行了尝试?你检查了吗?这就是我的想法来源,我的代码基于那个网站的示例。你的代码出了什么问题?@desbest我不知道,这就是为什么我在这里发布它…我认为代码对我来说非常有意义。。。但是结果总是我数据库的第一项,这是否意味着循环不起作用?还是循环在第一次之后停止?
<?php 
$input = 'inputWord';

$statement = $connection->prepare("SELECT name FROM `words`");
$statement->execute(array());
$rows = $statement->fetchAll();
$resultArray = [];

foreach ($rows as $row) {
    $compSum = 0;
    for ($i = 0; $i < strlen($row[0]) - 1; $i++) {
        $searchPosition = strpos($input, $row[0][$i] . $row[0][$i + 1]);
        if (is_numeric($searchPosition)) {
            $compSum += abs($searchPosition - $i);
        } else {
            $compSum += 10;
        }
    }
    $lenDiference = strlen($input) - strlen($row[0]);
    if ($lenDiference > 0) {
        $compSum += $lenDiference * 10;
    }
    $resultArray[] = array('word' => $row[0], 'compSum' => $compSum);
}

function sortBySum($a, $b) {
    return $b['compSum'] - $a['compSum'];
}

usort($resultArray, 'sortBySum');
$bestMatch = array_pop($resultArray);

echo 'Input word: ' . $input . '<br/>';
if ($bestMatch['compSum'] < 50) {
    echo 'Did you mean: ' . array_pop($resultArray)['word'];
}