如何从MYSQL / PHP中的数据中提取匹配的短语?

时间:2009-04-28 11:13:00

标签: php mysql search

我正在尝试在我的网站中实现搜索功能。我有以下类型的数据。

Title                Descr  
-----                ----- 
World News           World news, news from across the world, all world news events covered
World Sports         World sports news, for all of sports people, sports is a famous world

现在我想如果用户搜索“世界新闻”,那么结果将显示如下,

World News (title)
... all world news events covered ... (descr)

基本上我想随机显示一些短语。就像当用户搜索“世界新闻”时,有时他会得到上面的结果,有时候会像下面那样,

World News (title)
World news, news from across the world, ... (descr)

请告诉我如何使用mysql查询获得这种功能,或者如果不能直接通过mysql查询获得这种功能,那么如何使用PHP。

谷歌有时做同样的事情,谷歌显示中间的短语,有时它会显示起始文本。

感谢。

3 个答案:

答案 0 :(得分:1)

不确定是否有MySQL方法可以实现您的目标。我会从数据库中提取字段,然后使用PHP的explode()函数随机化一个短语:

$desc_field_result = "World news, news from across the world, all world news events covered"; // The "Desc" field from your MySQL Query

$desc_field_array = explode(",",$desc_field_result);

$selected_desc = $desc_field_array[rand(0,sizeof($desc_field_array)-1)];

echo $selected_desc;

答案 1 :(得分:0)

谷歌并不仅仅会返回一些随机句子。它返回一个包含您搜索的单词的片段(或两个)。 MySQL无法为您做到这一点。您需要在PHP中手动执行此操作(手动搜索返回的数据库行中的关键字并显示相关的代码段)或使用可以为您执行此操作的搜索引擎(例如Xapian,Sphinx或Apache Lucene)。 / p>

答案 2 :(得分:-3)

如果您的mysql表中存有标题和说明,请尝试以下方法:

SELECT descr FROM yourTable WHERE title='World News' ORDER BY RAND()

ORDER BY RAND()条件将从标题World news的条件匹配的行中随机选择