【问题标题】:Get search engine-like search body snippet using php使用 php 获取类似搜索引擎的搜索正文片段
【发布时间】:2011-05-09 05:47:05
【问题描述】:

我的网站搜索引擎完全按照我想要的方式运行,除了一个烦人的问题:我希望能够显示所有搜索引擎都会显示的那种搜索正文,它们会突出显示包含您的搜索的 1 到 3 个句子我的结果中的术语。

我的 Googlefoo 在这方面并不强,所以我希望有人可以让我使用现有的解决方案。

【问题讨论】:

  • 如何保存结果?有关结果及其来源的哪些信息可用?
  • 你用的是什么搜索引擎?

标签: php search search-engine


【解决方案1】:

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

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

您需要在纯文本上执行此操作,否则您可能会遇到 A List Apart 文章 Enhance Usability by Highlighting Search Terms 中提到的一些复杂情况;

您可以尝试基于 Javascript 的方法,但基于 PHP/HTML 的方法会更容易访问。

【讨论】:

    【解决方案2】:

    如果您不想像 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-07
      • 1970-01-01
      • 1970-01-01
      • 2010-10-04
      • 1970-01-01
      • 2012-04-10
      • 2013-09-03
      相关资源
      最近更新 更多