在ASP.Net中搜索关键字高亮显示

时间:2009-10-27 10:31:39

标签: c# .net asp.net search highlighting

我正在输出给定字符串关键字的搜索结果列表,我希望我的搜索结果中的任何匹配关键字都会突出显示。每个单词应包含在跨度或类似内容中。我正在寻找一种有效的功能来实现这一目标。

E.g。

关键词:“lorem ipsum”

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

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

我的结果不区分大小写。

5 个答案:

答案 0 :(得分:13)

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

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;
}

还有其他建议或意见吗?

答案 1 :(得分:1)

答案 2 :(得分:1)

使用jquery高亮插件。

在服务器端突出显示

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中编写上述代码,以便在其他应用程序中重复使用。

答案 3 :(得分:0)

我在ASP.NET中有类似的要求。这是我用C#编写的高亮关键字解决方案。

Algo使用的是朴素搜索算法。

  • 维护一个哈希表以存储匹配项。
  • 在有关键字匹配的字符串上应用标记。

    区域突出显示

        /// <summary>
        /// Higlight the search term.
        /// </summary>
        /// <param name="currentString"></param>
        /// <returns></returns>
        private string Highlight(string currentString)
        {
            try
            {
                var termValue = _helperRequest.SearchText;
                if (!string.IsNullOrEmpty(currentString) && !string.IsNullOrEmpty(termValue))
                {
                    currentString = termValue.Trim().Split(Constants.Separator)
                                                    .ToList().Where(x => x.Length >1)
                                                    .Distinct()
                                                    .OrderByDescending(x => x.Length)
                                                    .Aggregate(currentString, (current, keyWord) =>
                                                     TagIndexers(new SearchHelperRequest() { SearchString = current, SearchTerm = keyWord, HightlightCss = _helperRequest.HightlightCss, Comparison = StringComparison.InvariantCultureIgnoreCase, TagIdentifier = GetRandomKey() }));
                }
            }
            catch (Exception ex)
            {
                Logger.WriteError(string.Format("Highlight Error : {0}", ex.Message));
            }
            finally
            {
                //Replace tags with highlight terms.
                if (_helperRequest != null)
                {
                    if (_helperRequest.TagKeyLookup.Keys.Count > 0)
                    {
                        foreach (string tagKey in _helperRequest.TagKeyLookup.Keys)
                        {
                            if (!string.IsNullOrEmpty(currentString))
                                currentString = currentString.Replace(tagKey, _helperRequest.TagKeyLookup[tagKey]);
                        }
    
                        //clear the key list.
                        _helperRequest.TagKeyLookup.Clear();
                    }
                }
            }
            return HttpUtility.JavaScriptStringEncode(currentString);
        }
        /// <summary>
        /// Generate a randome key from lookup table. Recurrsive in  nature.
        /// </summary>
        /// <returns></returns>
        private string GetRandomKey()
        {
            //config your key length
            var charBuffer = new char[4];
            lock (charBuffer)
            {
                for (var iCounter = 0; iCounter < charBuffer.Length; iCounter++)
                {
                    charBuffer[iCounter] = CharacterLookup
                        [new Random().Next(CharacterLookup.Length)];
                }
            }
            //Recurssion to generate random.
            return _helperRequest.TagKeyLookup.
                ContainsKey(new String(charBuffer))
                ? GetRandomKey() : new String(charBuffer);
        }
        /// <summary>
        /// Replace the term with identifiers
        /// </summary>
        /// <param name="searchRequest"></param>
        /// <returns></returns>
        private string TagIndexers(SearchHelperRequest searchRequest)
        {
            try
            {
                var highlightBulder = new StringBuilder();
                string spanValue = string.Empty;
                if (!string.IsNullOrEmpty(searchRequest.SearchString) && !string.IsNullOrEmpty(searchRequest.SearchTerm))
                {
                    int previousIndex = 0;
                    int currentIndex = searchRequest.SearchString.IndexOf(searchRequest.SearchTerm, searchRequest.Comparison);
                    while (currentIndex != -1)
                    {
                        highlightBulder.Append(searchRequest.SearchString.Substring(previousIndex, currentIndex - previousIndex));
                        spanValue = string.Format(searchRequest.HightlightCss, searchRequest.SearchString.Substring(currentIndex, searchRequest.SearchTerm.Length));
                        highlightBulder.Append(searchRequest.TagIdentifier);
                        currentIndex += searchRequest.SearchTerm.Length;
                        previousIndex = currentIndex;
                        currentIndex = searchRequest.SearchString.IndexOf(searchRequest.SearchTerm, currentIndex, searchRequest.Comparison);
                    }
                    if (!_helperRequest.TagKeyLookup.ContainsKey(searchRequest.TagIdentifier) &&
                        !string.IsNullOrEmpty(spanValue))
                    {
                        _helperRequest.TagKeyLookup.Add(searchRequest.TagIdentifier, spanValue);
                    }
                    highlightBulder.Append(searchRequest.SearchString.Substring(previousIndex));
                }
                return highlightBulder.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
    private static char[] _characterLookup = null;
        public char[] CharacterLookup
        {
            get
            {
                if (_characterLookup == null)
                {
                    _characterLookup = new char[36];
    
                    lock (_characterLookup)
                    {
                        int indexer = 0;
                        //build the table.
                        for (char c = '0'; c <= '9'; c++) _characterLookup[indexer++] = c;
                        for (char c = 'A'; c <= 'Z'; c++) _characterLookup[indexer++] = c;
                    }
                }
                return _characterLookup;
            }
        }
    

**例程摘要:

  • 搜索字词并应用标记。
  • 将唯一标记存储在哈希表中。
  • 用Span Highlights替换标签。**

答案 4 :(得分:0)

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

为了避免在搜索条件为[span pan a a]时替换范围,找到的单词被替换为除了替换之外的其他内容......虽然效率不高......

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;
}