在搜尋關鍵詞高亮中一般的方法都是採用替換的辦法(Replace)這個方法有一個缺點就是不能區分大小寫問題。在網上找了找發現有人用Regex的方法來解決這個問題還真不錯,效率也比較高,歸納如下,有用得到的朋友可以一試。
//搜尋關鍵詞高亮顯示函數 public static string HighLightKeyWord(string pain,string keyword) {
//搜尋關鍵詞高亮函數By JN 2006.11.30 System.Text.RegularExpressions.MatchCollection m = Regex.Matches(pain, keyword, RegexOptions.IgnoreCase); //忽略大小寫搜尋字串中的關鍵字 for (int j = 0; j < m.Count; j++)//迴圈在匹配的子串前後插東東 { //j×31為插入html標籤使pain字串增加的長度: pain = pain.Insert((m[j].Index + keyword.Length + j * 31), "</font>");//關鍵字後插入html標籤 pain = pain.Insert((m[j].Index + j * 31), "<font color=#ff0000>");//關鍵字前插入html標籤 }
//搜尋關鍵詞高亮函數By JN 2006.11.30 return pain; }
當然用之前引用先:using System.Web.UI.HtmlControls;
還有:using System.Text.RegularExpressions;(小魚加)
以上代碼有問題:同一句中有多個關鍵字時出問題
試一下這個先
/// <summary> /// 替換關鍵字為紅色 /// </summary> /// <param name="keycontent">原始內容</param> /// <param name="k">關鍵字,支援多關鍵字</param> /// <returns>String</returns> /// <author>haver Guo</author> public static string Highlightkeywords(string keycontent, string k) { string resultstr = keycontent; if (k.Trim().IndexOf(' ') > 0) { string[] myArray = k.Split(' '); for (int i = 0; i < myArray.Length; i++) { resultstr = resultstr.Replace(myArray[i].ToString(), "<font color=#FF0000>" + myArray[i].ToString() + "</font>"); } return resultstr; } else { return resultstr.Replace(k, "<font color=#FF0000>" + k + "</font>"); } } 經測,可用
public static string red(string theField, string fkeywords)
{
string red;
red = theField.Replace(fkeywords,
"<font color=\"red\">" + fkeywords + "</font>");
return red;
}