我有一個體面的輕量級搜索引擎,爲我的網站之一使用MySQL全文索引和php來分析結果。工作正常,但我想通過結果中的文本片段和突出顯示的單詞提供更多'類似谷歌'的結果。尋找一個基於PHP的解決方案。任何建議?從實際結果中顯示帶有關聯文本片段的搜索結果的最佳實踐
4
A
回答
5
搜索實際的數據庫是好的,直到你想添加像上面這樣的時髦功能。根據我的經驗,最好創建一個專用的搜索表,包含關鍵字和頁面ID/URL /等。然後填充此表格每n小時的內容。在此人口中,您可以爲每個關鍵字的每個文檔添加片段。
或者一個快速的黑客可能是:
<?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;
?>
1
使用preg_replace()
(或類似的函數)並用突出顯示的文本替換搜索字符串。例如
$highlighted_text = preg_replace("/$search/", "<span class='highlighted'>$search</span>", $full_text);
+1
突出的方式是不是我的問題。我想知道最好的方式去獲取片段_around_搜索詞。 – phirschybar 2009-07-28 20:13:00
3
對於MySQL,最好的辦法是首先分散你的查詢詞,清理你的價值觀,然後串聯一切回到一個漂亮的正則表達式。
爲了突出顯示結果,您可以使用<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_headline
as described in the documentation。
-1
在一個較大的網站,我會認爲使用JavaScript,像jQuery的是去
相關問題
- 1. 搜索結果分頁,最佳實踐
- 2. 最佳實踐結果
- 3. 最佳實踐關閉JDBC結果
- 4. 顯示實時搜索結果AJAX
- 5. 如何顯示實時搜索結果
- 6. C#爲搜索結果顯示找到相關文檔片段
- 7. 顯式等待最準確結果的最佳實踐
- 8. 片段的最佳實踐
- 9. 實例化結果集中的對象...最佳實踐?
- 10. Solr搜索字段最佳實踐
- 11. 動態搜索字段,最佳實踐?
- 12. 片段最佳實踐
- 13. 片段最佳實踐 - Android
- 14. 搜索結果(顯示更多結果)
- 15. ListView和sqlite的結果集搜索/過濾器(性能和最佳實踐)
- 16. Twitter的Twitter搜索結果中未顯示帶有照片的推文
- 17. 全文搜索沒有顯示結果
- 18. 實時搜索結果
- 19. 從搜索結果預覽片段中排除文本?
- 20. 結合JS文件的最佳實踐
- 21. 迭代Postgres/PHP/PDO中結果集的最佳實踐?
- 22. 在Python中操作數據庫結果集的最佳實踐?
- 23. SSRS 2012中單值結果的最佳實踐
- 24. Perl搜索僅顯示最後結果
- 25. Drupal:顯示最近搜索結果
- 26. Java和Selenium顯示Google搜索結果的最佳方式
- 27. 加速搜索結果顯示的最佳方式
- 28. 從靜止頁面獲取頁面結果API:最佳實踐
- 29. Oracle - 搜索文本 - 檢索結果的代碼片段
- 30. 只顯示相關搜索結果
我喜歡這個解決方案。我有相當輕的流量,因此每個搜索請求的額外處理都很好。謝謝!! – phirschybar 2009-07-31 18:54:00