7

特定のキーワード文字列の検索結果のリストを出力しています。検索結果で一致するキーワードを強調表示したいと考えています。各単語はスパンまたは同様のもので囲む必要があります。これを行うための効率的な関数を探しています。

例えば

キーワード: "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 ハイライト プラグインを使用します。

サーバー側で強調表示するため

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 が置き換えられないようにするために、見つかった単語は、replace back 以外の何かに置き換えられました...あまり効率的ではありませんが...

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 に答える