代码之家  ›  专栏  ›  技术社区  ›  phirschybar

显示搜索结果和实际结果中关联的文本片段的最佳实践

  •  4
  • phirschybar  · 技术社区  · 15 年前

    我有一个体面的,轻量级的搜索引擎,我的一个网站使用mysql全文索引和php来解析结果。工作得很好,但我想提供更多类似谷歌的搜索结果,其中包括搜索结果的文本片段和突出显示的单词。正在查找基于PHP的解决方案。有什么建议吗?

    4 回复  |  直到 12 年前
        1
  •  5
  •   Al.    15 年前

    搜索实际的数据库是可以的,直到您想添加像上面这样时髦的功能。根据我的经验,最好创建一个带有关键字和页面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;
    ?>
    
        2
  •  3
  •   adamdehaven    12 年前

    对于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 .

        3
  •  1
  •   Brian Ramsay    15 年前

    使用 preg_replace() (或类似功能)并用突出显示的文本替换搜索字符串。例如

    $highlighted_text = preg_replace("/$search/", "<span class='highlighted'>$search</span>", $full_text);
    
        4
  •  -1
  •   JasonDavis    15 年前

    在一个更大的站点上,我认为使用Javascript,像jquery这样的东西是可行的。