【问题标题】:Best practices on displaying search results with associated text snippets from actual result显示搜索结果与实际结果中的相关文本片段的最佳实践
【发布时间】:2009-07-28 18:38:13
【问题描述】:

我有一个体面的、轻量级的搜索引擎,它使用 MySQL 全文索引和 php 来解析结果。工作正常,但我想提供更多“类似谷歌”的结果,其中包含来自结果的文本 sn-ps 并突出显示找到的单词。寻找基于 php 的解决方案。有什么建议吗?

【问题讨论】:

    标签: php mysql search


    【解决方案1】:

    搜索实际的数据库是没问题的,直到您想要添加像上面这样的时髦功能。根据我的经验,最好创建一个专用的搜索表,其中包含关键字和页面 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;
    ?>
    

    【讨论】:

    • 我喜欢这个解决方案。我的流量相当小,所以对每个搜索请求的额外处理都很好。谢谢!!
    • 可能想要将 strpos 更改为 stripos,并将 str_replace 更改为 preg_replace 以保持大小写。即,如果搜索“汉堡”,您不希望将粗体文本更改为“汉堡”。 preg_replace('/('.$keyword.')/i', '$1', $sn-p);
    【解决方案2】:

    对于 MySQL,最好的办法是首先拆分查询词,清理值,然后将所有内容连接回一个不错的正则表达式。

    为了突出显示您的结果,您可以使用&lt;strong&gt; 标签。它的用法将是语义上的,因为您将 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

    【讨论】:

      【解决方案3】:

      使用preg_replace()(或类似函数)并将您的搜索字符串替换为突出显示的文本。例如

      $highlighted_text = preg_replace("/$search/", "<span class='highlighted'>$search</span>", $full_text);
      

      【讨论】:

      • 突出显示不是我的问题。我想知道让 sn-p 围绕搜索词的最佳方法。
      【解决方案4】:

      在更大的网站上,我认为使用 javascript,像 jquery 之类的东西会是要走的路

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-01
        • 1970-01-01
        • 2014-12-06
        • 1970-01-01
        • 2023-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多