Search keyword highlight in ASP.Net

后端 未结 4 423
悲哀的现实
悲哀的现实 2021-02-04 17:23

I am outputting a list of search results for a given string of keywords, and I want any matching keywords in my search results to be highlighted. Each word should be wrapped in

4条回答
  •  孤独总比滥情好
    2021-02-04 17:58

    An extension to the answer above. (don't have enough reputation to give comment)

    To avoid span from being replaced when search criteria were [span pan an a], the found word was replaced to something else than replace back... not very efficient though...

    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("{0}", 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("{0}", sKeyword);
        }
    
        for (int i = totalCount - 1; i >= 0; i--)
        {
            input = Regex.Replace(input, "\\~" + i + "\\~", sHighlights[i], RegexOptions.IgnoreCase);
        }
    
        return input;
    }
    

提交回复
热议问题