Go homepage(回首页)
Upload pictures (上传图片)
Write articles (发文字帖)

The author:(作者)归海一刀
published in(发表于) 2014/1/30 1:21:59
asp.net搜索关键词高亮显示函数_[Asp.Net教程]

asp.net搜索关键词高亮显示函数_[Asp.Net教程]
在搜索关键词高亮中一般的方法都是采用替换的办法(Replace)这个方法有一个缺点就是不能区分大小写的问题。在网上找了找发现有人用正则表达式的方法来解决这个问题还真不错,效率也比较高,归纳如下,有用得到的朋友可以一试。
//搜索关键词高亮显示函数
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), "");//关键字后插入html标签
pain = pain.Insert((m[j].Index + j * 31), "");//关键字前插入html标签
}
//搜索关键词高亮函数By JN 2006.11.30
return pain;
}
当然用之前引用先:using System.Web.UI.HtmlControls;
还有:using System.Text.RegularExpressions;(小鱼加)
以上代码有问题:同一句中有多个关键字时出问题
试一下这个先
///
/// 替换关键字为红色
///

/// 原始内容
/// 关键字,支持多关键字
/// String
/// haver Guo
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(), "" + myArray[i].ToString() + "");
}
return resultstr;
}
else
{
return resultstr.Replace(k, "" + k + "");
}
}
经测,可用


If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)





QQ:154298438
QQ:417480759