在搜索关键词高亮中一般的方法都是采用替换的办法(Replace)这个方法有一个缺点就是不能区分大小写的问题。在网上找了找发现有人用正则表达式的方法来解决这个问题还真不错,效率也比较高,归纳如下,有用得到的朋友可以一试。

 

        //搜索关键词高亮显示函数
        public static string HighLightKeyWord(string pain,string keyword)
        {

            //搜索关键词高亮函数
            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), "</font>");//关键字后插入html标签
                pain = pain.Insert((m[j].Index + j * 31), "<font color=#ff0000>");//关键字前插入html标签
            }

            //搜索关键词高亮函数By JN 2006.11.30
            return pain;
        }

 

当然用之前引用先:using System.Web.UI.HtmlControls;

-----------------------------------------------------------------

// 不区分大小写高亮的。
static string HighlightKeyword(string str, string keyword)
{
int index;
int startIndex = 0;
string highlightBegin = "<span style='background-color:#FFEE62'>";
string highlightEnd = "</span>";
int length = highlightBegin.Length + keyword.Length;
int lengthHighlight = length + highlightEnd.Length;
while ((index = str.IndexOf(keyword, startIndex, StringComparison.OrdinalIgnoreCase)) > -1)
{
str = str.Insert(index, highlightBegin).Insert(index + length, highlightEnd);
startIndex = index + lengthHighlight;
}
return str;
}
posted on 2008-10-07 10:16  李辉明  阅读(1119)  评论(0编辑  收藏  举报