一、问题的产生 搜索结果高亮显示,在新闻标题,来源之类的地方好做,只需要用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);//替换关键字为高亮显示