【发布时间】:2009-07-28 18:38:13
【问题描述】:
我有一个体面的、轻量级的搜索引擎,它使用 MySQL 全文索引和 php 来解析结果。工作正常,但我想提供更多“类似谷歌”的结果,其中包含来自结果的文本 sn-ps 并突出显示找到的单词。寻找基于 php 的解决方案。有什么建议吗?
【问题讨论】:
我有一个体面的、轻量级的搜索引擎,它使用 MySQL 全文索引和 php 来解析结果。工作正常,但我想提供更多“类似谷歌”的结果,其中包含来自结果的文本 sn-ps 并突出显示找到的单词。寻找基于 php 的解决方案。有什么建议吗?
【问题讨论】:
搜索实际的数据库是没问题的,直到您想要添加像上面这样的时髦功能。根据我的经验,最好创建一个专用的搜索表,其中包含关键字和页面 ID/URL/等。然后每隔 n 小时用内容填充此表。在此填充期间,您可以为每个关键字的每个文档添加 sn-ps。
另外一种快速破解方法可能是:
<?php
$text = 'This is an example text page with content. It could be red, green or blue.';
$keyword = 'red';
$size = 5; // size of snippet either side of keyword
$snippet = '...'.substr($text, strpos($text, $keyword) - $size, strpos($text, $keyword) + sizeof($keyword) + $size).'...';
$snippet = str_replace($keyword, '<strong>'.$keyword.'</strong>', $snippet);
echo $snippet;
?>
【讨论】:
对于 MySQL,最好的办法是首先拆分查询词,清理值,然后将所有内容连接回一个不错的正则表达式。
为了突出显示您的结果,您可以使用<strong> 标签。它的用法将是语义上的,因为您将 strong 重点放在一个项目上。
// Done ONCE per page load:
$search = "Hello World";
//Remove the quotes and stop words
$search = str_ireplace(array('"', 'and', 'or'), array('', '', ''), $search);
// Get the words array
$words = explode(' ', $search);
// Clean the array, remove duplicates, etc.
function remove_empty_values($value) { return trim($value) != ''; }
function regex_escape(&$value) { $value = preg_quote($value, '/'); }
$words = array_filter($words, 'remove_empty_values');
$words = array_unique($words);
array_walk($words, 'regex_escape');
$regex = '/(' . implode('|', $words) . ')/gi';
// Done FOR EACH result
$result = "Something something hello there yes world fun nice";
$highlighted = preg_replace($regex, '<strong>$0</strong>', $result);
如果你使用的是PostgreSQL,你可以简单地使用内置的ts_headlineas described in the documentation。
【讨论】:
使用preg_replace()(或类似函数)并将您的搜索字符串替换为突出显示的文本。例如
$highlighted_text = preg_replace("/$search/", "<span class='highlighted'>$search</span>", $full_text);
【讨论】:
在更大的网站上,我认为使用 javascript,像 jquery 之类的东西会是要走的路
【讨论】: