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