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

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

例如

关键词:“lorem ipsum”

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

期望的HTML输出:“ Some text containing lorem and ipsum

我的结果不区分大小写。

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

 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("{0}", "$0"), RegexOptions.IgnoreCase); } catch { // } } return input; } 

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

使用jquery高亮插件。

用于在服务器端突出显示它

 protected override void Render( HtmlTextWriter writer ) { StringBuilder html = new StringBuilder(); HtmlTextWriter w = new HtmlTextWriter( new StringWriter( html ) ); base.Render( w ); html.Replace( "lorem", "lorem" ); writer.Write( html.ToString() ); } 

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

您还可以在HttpModule中编写上述代码,以便可以在其他应用程序中重复使用。

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

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

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

    区域突出显示

      ///  /// Higlight the search term. ///  ///  ///  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); } ///  /// Generate a randome key from lookup table. Recurrsive in nature. ///  ///  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); } ///  /// Replace the term with identifiers ///  ///  ///  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替换标签。**

以上答案的延伸。 (没有足够的声誉来发表评论)

为了避免在搜索条件为[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("{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; }