Domanda

Sto producendo un elenco di risultati di ricerca per una determinata stringa di parole chiave e desidero evidenziare eventuali parole chiave corrispondenti nei miei risultati di ricerca. Ogni parola dovrebbe essere racchiusa in un arco o simile. Sto cercando una funzione efficiente per farlo.

per es.

Parole chiave: " lorem ipsum "

Risultato: " Alcuni testi contenenti lorem e ipsum "

Output HTML desiderato: " Some text containing <span class="hit">lorem</span> and <span class="hit">ipsum</span> "

I miei risultati non fanno distinzione tra maiuscole e minuscole.

È stato utile?

Soluzione

Ecco cosa ho deciso. Una funzione di estensione che posso chiamare sulle stringhe pertinenti all'interno della mia pagina / sezione della mia pagina:

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

Ulteriori suggerimenti o commenti?

Altri suggerimenti

Utilizza il plug-in di evidenziazione di jquery.

Per evidenziarlo sul lato server

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

Puoi utilizzare espressioni regolari per la sostituzione avanzata del testo.

Puoi anche scrivere il codice sopra in un HttpModule in modo che possa essere riutilizzato in altre applicazioni.

Ho un requisito simile da fare in ASP.NET. Ecco la mia soluzione scritta in C # per la parola chiave highlight.

Algo utilizzato è l'algoritmo di ricerca ingenuo.

  • Mantieni una tabella hash per archiviare le partite.
  • Applica tag sulla stringa in cui è presente una corrispondenza di parole chiave.

    Evidenziazione della regione

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

** Riepilogo delle routine:

  • Cerca il termine e applica i tag.
  • Archivia tag univoci in una tabella hash.
  • Sostituisci i tag con gli span highlight. **

Un'estensione alla risposta sopra. (non hai abbastanza reputazione per commentare)

Per evitare che lo span venga sostituito quando i criteri di ricerca erano [span pan an a], la parola trovata è stata sostituita con qualcos'altro che sostituire back ... non molto efficiente però ...

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;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top