MySQL列格,计算与查询匹配的单词数?

时间:2012-07-17 06:31:50

标签: mysql sql

我正在尝试根据查询中在行中找到的单词数对匹配进行评分。我盯着这样做:

SELECT Text, MATCH(`Text`) AGAINST ('$s') AS Grade

但很快我意识到这不起作用,因为Grade基于很多东西,例如单词的顺序,每个单词的长度等等。

我只想知道连续出现的单词百分比。

EG:

$s = 'i want pizza'
`Text` = 'pizza I want' // In this case Grade should be 100 as all words are found

其他例子:

Text             | Grade
pizza I want too | 100 // All words were found, It doesn't matter if there are extra words
pizza I want     | 100
i want           | 66 // Only 66% of the words are present
want want want   | 33 // Only 33% of the words are present

1 个答案:

答案 0 :(得分:1)

$s = 'i want pizza';
$text = 'pizza I want';

//move to lower-case to ignore case-differences
$s = strtolower($s);
$text = strtolower($text);

//count the number of words in $s
$slen = count(explode(" ", $s));
//create an array of words from the text that we check
$arr = explode(" ", $text);
$count = 0;
//go over the words from $text and count words that appear on $s
foreach ($arr as $word) {
    if(strpos($s, $word) !== false){
        $count++;
    }
}
//display the percentage in format XX.XX
echo number_format((double)(100 * $count/$slen),2);