2009-07-28 21 views

回答

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; 
?> 
+0

我喜歡這個解決方案。我有相當輕的流量,因此每個搜索請求的額外處理都很好。謝謝!! – phirschybar 2009-07-31 18:54:00

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_headlineas described in the documentation

-1

在一個較大的網站,我會認爲使用JavaScript,像jQuery的是去