html 显示搜索结果,搜索结果高亮显示(不改变html标签)
一、問題的產生 搜索結果高亮顯示,在新聞標題,來源之類的地方好做,只需要用str.Replace(keyword,"font style=/"color:red;/"" + keyword +"/font");這樣的方法就可實現。 例如:新聞內容里的圖片img alt="" src="Upload/1.jpg" /,搜索時使用的關鍵字為oa
一、問題的產生
搜索結果高亮顯示,在新聞標題,來源之類的地方好做,只需要用str.Replace(keyword,"");這樣的方法就可實現。
例如:新聞內容里的圖片,搜索時使用的關鍵字為oa,則會將新聞內容中這張圖片替換為oad/1.jpg" />,這張圖片就顯示不出來了。
二、實現原理
再次,將搜索結果替換為高亮顯示狀態;
三、實現代碼
以下代碼是網上搜集的,來源不詳,在此對作者表示感謝。
public static string Reg(string input, string replace)
{
//設置高亮樣式
string replaceformat = "";
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(String.Format("{0}", replace), System.Text.RegularExpressions.RegexOptions.Multiline);
return reg.Replace(input, string.Format(replaceformat, replace));
}
///
/// 設置各個html部分為自定義標號
///
/// 輸入內容
/// 匹配集合
/// 替換的字串
public static string protectHtml(string input, ref System.Text.RegularExpressions.MatchCollection matches)
{
//匹配html的正則
System.Text.RegularExpressions.Regex htmlReg =
new System.Text.RegularExpressions.Regex(@"/<.>", System.Text.RegularExpressions.RegexOptions.Multiline);
//獲取匹配集合
matches = htmlReg.Matches(input);
//設置替換字串
string markFormat = "[[{0}]]";
//替換html,記錄位置
for (int i = 0; i < matches.Count; i++)
{
input = input.Replace(matches[i].Value, string.Format(markFormat, i));
}
return input;
}
///
/// 將標號恢復html
///
/// 高亮設置好的字串
/// 匹配集合
/// 最終字串
public static string restoreHtml(string input, System.Text.RegularExpressions.MatchCollection matches)
{
//設置替換字串
string markFormat = "[[{0}]]";
for (int i = 0; i < matches.Count; i++)
{
input = input.Replace(string.Format(markFormat, i), matches[i].Value);
}
return input;
}
使用方法:
System.Text.RegularExpressions.MatchCollection matches = null;
temp = Reg(temp, KeyWords);//替換關鍵字為高亮顯示
總結
以上是生活随笔為你收集整理的html 显示搜索结果,搜索结果高亮显示(不改变html标签)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 三星.android beam,三星S
- 下一篇: web.xml隐藏html,web.xm