一、问题的产生
搜索结果高亮显示,在新闻标题,来源之类的地方好做,只需要用str.Replace(keyword,"<font style=/"color:red;/"" + keyword +"</font>");这样的方法就可实现。
问题在于,在新闻内容里做搜索。其中html标签里可能含有关键字,用上面这种方法,将会替换掉html标签的部分内容,导致新闻内容不能正常显示。
例如:新闻内容里的图片<img alt="" src="Upload/1.jpg" />,搜索时使用的关键字为oa,则会将新闻内容中这张图片替换为<img alt="" src="Upl<font style="color:red;">oa</font>d/1.jpg" />,这张图片就显示不出来了。
二、实现原理
首先,将新闻内容里的所有html标签读出来,保存起来;
其次,将所有html标签替换为一般不可能出现的字符,如[[1]],[[2]]......[[N]]]等;(搜索的关键字一般不会是[[N]]吧,新闻内容里也一般不会出现这样的字符)
再次,将搜索结果替换为高亮显示状态;
最后,将html标签还原。
三、实现代码
以下代码是网上搜集的,来源不详,在此对作者表示感谢。
public static string Reg(string input, string replace)
{
//设置高亮样式
string replaceformat = "<span style=/"font-size:14px; font-weight:bold; color:#f00; {0}</span>";
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));
}
/// <summary>
/// 设置各个html部分为自定义标号
/// </summary>
/// <param name="input">输入内容</param>
/// <param name="matches">匹配集合</param>
/// <returns>替换的字串</returns>
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;
}
/// <summary>
/// 将标号恢复html
/// </summary>
/// <param name="input">高亮设置好的字串</param>
/// <param name="matches">匹配集合</param>
/// <returns>最终字串</returns>
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;
string temp = protectHtml(Contents, ref matches);//保护html标签
temp = Reg(temp, KeyWords);//替换关键字为高亮显示
Contents = restoreHtml(temp, matches);//恢复html标签