asp.net(C#)中自动替换html标签示例
namespaceAutoPage
{
publicclassOtherCs
{
publicstaticstringReplaceHtml(stringoldStr)
{
/*顺序不可变,特别是将<与>替换成"<"与" >"的一定要在其它替换前,因为如果把它放在其它替后,它就会把其它替换后的<与>也替换成"<"和" >"了。*/
newStr=newStr.Replace("<","lt;");
newStr=newStr.Replace(">","gt;");
newStr=newStr.Replace("","nbsp;");
newStr=newStr.Replace("[code]","<spanclass=\"code\">");
newStr=newStr.Replace("[/code]","</span>");
newStr=newStr.Replace("[strong]","<strong>");
newStr=newStr.Replace("[/strong]","</strong>");
newStr=newStr.Replace("[p]","<p>");
newStr=newStr.Replace("[/p]","</p>");
newStr=newStr.Replace("\r\n","<br/>");
//替换[URL]标签,即<a>标签,这里就要用到正则了。
//先匹配出需要替换成a标签的全部部分。用户录入的原始值类似于:[URLhref="http://www.lmwlove.com"]程序食堂[/URL]
stringregstr_1="\\[URL\\s*href=(['\"\\s]?)[^'\"\\s]+\\1\\][^\\[\\]]+\\[/URL]";
//匹配[URLhref="http://www.lmwlove.com"]程序食堂[/URL]中的http://www.lmwlove.com,即url地址
stringregstr_2=@"http://([\w-]+\.)+[\w-]+(/[\w-./?%=]*)?";
//匹配[URLhref="http://www.lmwlove.com"]程序食堂[/URL]中的程序食堂,即url中的文本
stringregstr_3=@"\]+[^\[\]]+(\[+)";
stringurl=string.Empty;
stringurlname=string.Empty;
Regexregex=newRegex(regstr_1);
MatchCollectionmatchs=regex.Matches(newStr);
foreach(Matchminmatchs)
{
Regexregex_1=newRegex(regstr_2);
Matchmatch=regex_1.Match(m.Value);
if(match.Success)
{
url=match.Value;
}
regex_1=newRegex(regstr_3);
match=regex_1.Match(m.Value);
if(match.Success)
{
urlname=match.Value.Substring(1,match.Value.Length-2);
}
//筛选出了链接的url与文本后,重新组织正确的<a>标签
newStr=newStr.Replace(m.Value,"<ahref=\""+url+"\"target=\"_blank\"class=\"content_href\">"+urlname+"</a>");
}
returnnewStr;
}
}
}
- 上一篇: SmartGrid列基类SmartGridColumn列详解
- 下一篇: 返回列表