简体   繁体   English

如何将句子中的关键字与数据库表中的现有句子匹配?

[英]How to match key words in a sentence against pre-existing sentences in a database table?

I want insert "This is a apple, it is a fruit" to query the database, and only match the words 'apple' and 'fruit' not 'fruits' from the database and return '1 fruit apple red 10'. 我想插入“这是一个苹果,这是一个水果”来查询数据库,并且只匹配数据库中的单词“ apple”和“ fruit”而不是“ fruits”,并返回“ 1 fruit apple red 10”。

How to modify the query code? 如何修改查询代码?

Database name 'food' fields as below: 数据库名称“食品”字段如下:

id name1 name2 name3 name4 type
1 fruit apple red 10 article
2 fruit banana yellow 12 article
3 drink beer yellow 6 article
4 fruits apple yellow 16 books

Code: 码:

mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("article") or die(mysql_error());
... ...
echo $match . "r"; // $match= This is a apple, it is a fruit
$query = mysql_query("SELECT * FROM food WHERE name1, name2 like '%$match%' ");
$row=mysql_fetch_array($query);
echo $row['id ']. "r" .$row['name1']. "r".$row['name2']. "r".$row['name3']. "r".$row['name4']. "n";

It's hard to tell, but I think if you are trying to avoid returning anything that does not equal the exact word (apples != apple). 很难说,但我认为如果您要避免返回不等于确切单词的任何内容(apples!= apple)。 You will have to break your $match string into smaller parts and check for them individually. 您将必须将$ match字符串分成较小的部分,并分别进行检查。 maybe use explode() to break the string apart using white spaces and then do exact matches on the words that apply. 也许使用explode()使用空格将字符串分开,然后对要应用的单词进行完全匹配。

Currently, You are checking for any data in the database that could resemble the string in anyway whatsoever. 当前,您正在检查数据库中任何可能与字符串相似的数据。 So it could return "pineapple is a fruit" just because it has the words "is", "a" and "fruit". 因此它可能会返回“菠萝是一种水果”,因为它具有“ is”,“ a”和“ fruit”字样。

It might also be worth it to rename your database columns. 重命名数据库列也可能值得。 Nobody whats you look a code with name1,name2,name3.... how about type,name,color,amount? 没人看你的名字,名字2,名字3 ....的代码。类型,名字,颜色,数量怎么样?

$match = trim($match);
$match = strtolower($match);
$newmatch = explode(" ",$newmatch);

So if $match was "This is an apple" $newmatch = array("this","is","an","apple") 因此,如果$ match是“这是一个苹果”,则$ newmatch = array(“ this”,“ is”,“ an”,“ apple”)

Of course, this wont get rid of any punctuation. 当然,这不会消除任何标点符号。 But you can do before hand if you like with trim and preg_replace. 但是,如果您愿意使用trim和preg_replace,则可以事前准备。

Help: trim() , strtolower() , explode() 帮助: trim()strtolower()explode()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM