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

使用php获取类似搜索引擎的搜索正文片段

  •  2
  • S16  · 技术社区  · 13 年前

    我有我的网站搜索引擎的运作方式正是我想要的,除了一个烦人的问题:我想能够显示的搜索机构,所有的搜索引擎显示,他们强调1至3句话,包含你的搜索词在我的结果。

    2 回复  |  直到 13 年前
        1
  •  2
  •   Ross    13 年前

    如果你不想像battal建议的那样突出关键词,并且想截取相关段落/内容,我会这样做:

    $snippets = array();
    foreach ($matches as $i => $match) {
        $pos = strpos($match, $searchTerm);
    
        $buffer = 30; // characters before and after the search term is found
        // start index - 0 or 30 characters before instance of search term
        $start = ($pos - $buffer >= 0) ? $pos - $buffer : 0;
        // end index - 30 characters after instance of search term or the length of the match
        $end = $start + strlen($searchTerm) + $buffer;
        $end = ($end >= strlen($match)) ? strlen($match) : $end;
    
        $snippets[$i] = substr($match, $start, $end);
    }
    
        2
  •  0
  •   Halil Özgür    13 年前

    你的意思是搜索突出显示:

    str_replace(
        $searchTerm,  
        '<span class="searchHighlight">'.$searchTerm.'</span>',
        $searchString);
    

    你需要用纯文本来做,否则你可能会遇到一些复杂的问题,如一篇单列文章中提到的 Enhance Usability by Highlighting Search Terms ;