现在的位置: 首页 > 综合 > 正文

ASP.NET替换HTML代码中的任意代码

2013年03月29日 ⁄ 综合 ⁄ 共 2481字 ⁄ 字号 评论关闭

ASP.NET替换HTML代码<>中的任意代码

替换<>中的任意代码.
方法如下:
protected string DealTo(string ProcStr)
{
    string[] strarr ={ "onclick", "onmouseover", "onmouseout", "ondblclick", "ondisposed", "oninit", "onkeydown", "onkeyup", "onkeypress", "onload", "onmousedown", "onmousemove", "onmouseup", "onperender", "onunload" };
    //需要替换的代码数组,可以自定义
    string replaceto = "rpt";
    string reStr = "";
    reStr = ProcStr;
    for (int i = 0; i < strarr.Length; i++)
    {
        reStr = CheckAndDeal(reStr, strarr[i], replaceto);
    }
    return reStr;
}

protected string CheckAndDeal(string checkStr,string repStr,string replaceTo)
{
    int strIndex;
    int strLen = 0;
   
    strLen = checkStr.Length;
    string returnStr="";
    string tempReplaceTo = "ASDFGHJKL";
    //临时替换字符串,可以使用任何字符串代替,但是需要保证字符串不在要处理的字符串中出现
   
    if (strLen <= 0)
    {
        return "";
    }
    strIndex = checkStr.IndexOf(repStr);
    if (strIndex != -1)//等于或者小于0的情况不用判断.可以直接返回原来的字符串.
    {
        while (checkStr.IndexOf(repStr) != -1)//循环判断是否能够匹配替换字符串.
        {
            int indexOfGreat = -1;
            int indexOfLess = -1;
            strIndex = checkStr.IndexOf(repStr);
            char[] chArr = checkStr.ToCharArray();
            //查找字符<和>
            char coms = ' ';
            for (int i = strIndex - 1; i >= 0; i--)
            {
                //string s = checkStr.Substring(i , 1);
                coms = chArr[i];
                if (coms == '>')
                {
                    break;
                }
                else if (coms == '<')
                {
                    indexOfLess = i;
                    break;
                }
            }
            for (int i = strIndex; i < strLen; i++)
            {
                //string s = checkStr.Substring(i, 1);
                coms = chArr[i];
                if (coms == '<')
                {
                    break;
                }
                else if (coms == '>')
                {
                    indexOfGreat = i;
                    break;
                }
            }
            string subleft = "";
            string subright = "";
            subleft = checkStr.Substring(0, checkStr.IndexOf(repStr));
            subright = checkStr.Substring((checkStr.IndexOf(repStr) + repStr.Length));

            if (indexOfGreat > -1 && indexOfLess > -1 && indexOfGreat > indexOfLess && indexOfGreat < strLen)
            //如果符合在<>中,则替换,否则先将查找到的字符串替换成临时字符串.
            {
                checkStr = subleft + replaceTo + subright;
            }
            else
            {
                checkStr = subleft + tempReplaceTo + subright;
            }
        }
        checkStr = checkStr.Replace(tempReplaceTo, repStr);//将临时字符串替换回原来的字符串.
        returnStr = checkStr;
    }
    else
    {
        returnStr = checkStr;
    }
    return returnStr;
}

抱歉!评论已关闭.