Php 显示与实际结果关联的文本片段的搜索结果的最佳实践
我有一个相当不错的轻量级搜索引擎,用于我的一个网站,使用MySQL全文索引和php解析结果。工作很好,但我想提供更多的“谷歌式”的结果与文本片段的结果和发现的话突出显示。正在寻找基于php的解决方案。有什么建议吗?使用Php 显示与实际结果关联的文本片段的搜索结果的最佳实践,php,mysql,search,Php,Mysql,Search,我有一个相当不错的轻量级搜索引擎,用于我的一个网站,使用MySQL全文索引和php解析结果。工作很好,但我想提供更多的“谷歌式”的结果与文本片段的结果和发现的话突出显示。正在寻找基于php的解决方案。有什么建议吗?使用preg_replace()(或类似函数)并用突出显示的文本替换搜索字符串。e、 g $highlighted_text = preg_replace("/$search/", "<span class='highlighted'>$search</span>
preg_replace()
(或类似函数)并用突出显示的文本替换搜索字符串。e、 g
$highlighted_text = preg_replace("/$search/", "<span class='highlighted'>$search</span>", $full_text);
$highlighted\u text=preg\u replace(“/$search/”、“$search”、$full\u text);
对于MySQL,最好的选择是首先拆分查询词,清理值,然后将所有内容连接回一个好的正则表达式
为了突出显示结果,可以使用
标记。当你强调一个项目时,它的用法是语义的
// 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);
//每页加载一次:
$search=“你好世界”;
//删除引号和停止字
$search=str_-ireplace(数组(“,”和“,”或”)、数组(“,”)、$search);
//获取单词数组
$words=explode(“”,$search);
//清理阵列、删除重复项等。
函数remove_empty_value($value){返回trim($value)!='';}
函数regex_escape(&$value){$value=preg_quote($value,'/');}
$words=array_filter($words,'remove_empty_value');
$words=array\u unique($words);
数组_walk($words,'regex_escape');
$regex='/('.introde('|',$words)。')/gi';
//为每个结果完成
$result=“某物某物你好那里是的世界很有趣很好”;
$highlighted=preg_replace($regex,$0,$result);
如果您使用的是PostgreSQL,您只需使用内置的
ts_headline
搜索实际的数据库就可以了,直到您想要添加像上面这样的时髦功能。根据我的经验,最好创建一个带有关键字和页面ID/URL/等的专用搜索表。然后每隔n小时用内容填充此表。Du在这个群体中,您可以为每个关键字的每个文档添加代码段
或者,快速破解可能是:
<?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;
?>
在一个更大的网站上,我认为使用javascript,像jquery这样的东西是最好的选择突出显示不是我的问题。我想知道获取搜索词周围的代码片段的最佳方法。我喜欢这个解决方案。我的流量相当小,所以每次搜索请求的额外处理都很好。谢谢!!米格ht要将strop更改为stripos,并将str_替换为preg_替换以保留大小写。即,如果搜索“Burgers”,您不希望粗体文本更改为“Burgers”。preg_替换(“/(“.$关键字”)/i”,“$1,$snippet);