forked from cyyself/mofu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mofu_core.php
49 lines (49 loc) · 1.68 KB
/
mofu_core.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
error_reporting(0);
include_once("prepare.php");
function mofu($query) {
$db = new PDO('mysql:host=your_db_host;dbname=your_data_base;charset=utf8', 'your_db_username', 'your_db_password');
$keyarr = explode(' ',trim(mofu_prepare($query)));
$result = array();
foreach ($keyarr as $key) {
$subkey = array();
$keylen = mb_strlen($key);
if ($keylen == 0) continue;
//构造subkey
if ($keylen == strlen($key)) {
//纯ASCII字符
if ($keylen <= 5) {
$subkey[0] = $key;
$subkey[1] = ' ' . $key . ' ';
}
else for ($i=0;$i<=$keylen-4;$i++) $subkey[$i] = mb_substr($key,$i,4);
}
else {
//非纯ASCII字符
if ($keylen <= 3) $subkey[0] = $key;//完全匹配
else for ($i=0;$i<=$keylen-2;$i++) $subkey[$i] = mb_substr($key,$i,2);//2字分词模糊匹配
}
//精确
$stmt = $db->prepare("SELECT `id` FROM `your_table_name` WHERE mofuindex LIKE :l");
$stmt->execute(array(':l' => '%' . $key . '%'));
$sqlresult = $stmt->fetchAll();
foreach($sqlresult as $row) $result[$row['id']] ++;
//准备模糊匹配
$curweight = array();
foreach ($subkey as $eachsubkey) {
//模糊
$stmt = $db->prepare("SELECT `id` FROM your_table_name WHERE mofuindex LIKE :l");
$stmt->execute(array(':l' => '%' . $eachsubkey . '%'));
$sqlresult = $stmt->fetchAll();
foreach($sqlresult as $row) $curweight[$row['id']] ++;
}
foreach ($curweight as $key => $row) $result[$key] += pow($row/count($subkey),2);
}
arsort($result);
return $result;
}
/*
Then you get a weight sorted array from function "mofu", you can do everything to output by the id you get.
Hope you enjoy this new way to build search on your website.
*/
?>