7

我正在输出给定关键字字符串的搜索结果列表,并且我希望突出显示搜索结果中的任何匹配关键字。每个单词都应该包含在 span 或类似内容中。我正在寻找一个有效的功能来做到这一点。

例如

关键词:“lorem ipsum”

结果:“一些包含 lorem 和 ipsum 的文本”

所需的 HTML 输出:“ Some text containing <span class="hit">lorem</span> and <span class="hit">ipsum</span>

我的结果不区分大小写。

4

4 回答 4

14

这是我决定的。我可以在我的页面/页面部分中的相关字符串上调用的扩展函数:

public static string HighlightKeywords(this string input, string keywords)
{
    if (input == string.Empty || keywords == string.Empty)
    {
        return input;
    }

    string[] sKeywords = keywords.Split(' ');
    foreach (string sKeyword in sKeywords)
    {
        try
        {
            input = Regex.Replace(input, sKeyword, string.Format("<span class=\"hit\">{0}</span>", "$0"), RegexOptions.IgnoreCase);
        }
        catch
        {
            //
        }
    }
    return input;
}

有任何进一步的建议或意见吗?

于 2009-10-27T14:48:18.513 回答
1

尝试来自 Lucene.net 的荧光笔

http://incubator.apache.org/lucene.net/docs/2.0/Highlighter.Net/Lucene.Net.Highlight.html

如何使用:

http://davidpodhola.blogspot.com/2008/02/how-to-highlight-phrase-on-results-from.html

编辑:只要 Lucene.net 荧光笔不适合这里新链接:

http://mhinze.com/archive/search-term-highlighter-httpmodule/

于 2009-10-27T10:40:04.800 回答
1

使用 jquery highlight 插件。

在服务器端突出显示它

protected override void Render( HtmlTextWriter writer )
{
    StringBuilder html = new StringBuilder();
    HtmlTextWriter w = new HtmlTextWriter( new StringWriter( html ) );

    base.Render( w );

    html.Replace( "lorem", "<span class=\"hit\">lorem</span>" );

    writer.Write( html.ToString() );
}

您可以使用正则表达式进行高级文本替换。

您也可以将上述代码写在一个 HttpModule 中,以便在其他应用程序中重复使用。

于 2009-10-27T10:42:35.093 回答
0

对上述答案的扩展。(没有足够的声誉发表评论)

当搜索条件为 [span pan an a] 时,为了避免 span 被替换,找到的单词被替换为其他东西而不是替换回来......虽然不是很有效......

public string Highlight(string input)
{
    if (input == string.Empty || searchQuery == string.Empty)
    {
        return input;
    }

    string[] sKeywords = searchQuery.Replace("~",String.Empty).Replace("  "," ").Trim().Split(' ');
    int totalCount = sKeywords.Length + 1;
    string[] sHighlights = new string[totalCount];
    int count = 0;

    input = Regex.Replace(input, Regex.Escape(searchQuery.Trim()), string.Format("~{0}~", count), RegexOptions.IgnoreCase);
    sHighlights[count] = string.Format("<span class=\"highlight\">{0}</span>", searchQuery);
    foreach (string sKeyword in sKeywords.OrderByDescending(s => s.Length))
    {
        count++;
        input = Regex.Replace(input, Regex.Escape(sKeyword), string.Format("~{0}~", count), RegexOptions.IgnoreCase);
        sHighlights[count] = string.Format("<span class=\"highlight\">{0}</span>", sKeyword);
    }

    for (int i = totalCount - 1; i >= 0; i--)
    {
        input = Regex.Replace(input, "\\~" + i + "\\~", sHighlights[i], RegexOptions.IgnoreCase);
    }

    return input;
}
于 2013-12-13T05:54:59.407 回答