45fan.com - 路饭网

搜索: 您的位置主页 > 网络频道 > 阅读资讯:如何在ASP.NET中自动给URL加上超链接?

如何在ASP.NET中自动给URL加上超链接?

2016-09-07 06:54:08 来源:www.45fan.com 【

如何在ASP.NET中自动给URL加上超链接?

在进行asp.net开发时,经常会遇到页面中有很多的Url或者E-mail,我想让其自动的添加超级链接。这里是采用了网上大多数朋友的做法,即用正则表达式进行替换。

一、写一个正则表达式进行替换的方法

public string Url_Rewrite ( string Text )
{
//用正则表达式识别URL超链接
Regex UrlRegex = new Regex(@"(http:////([/w.]+//?)/S*)" , RegexOptions.IgnoreCase | RegexOptions.Compiled);

MatchCollection matches = UrlRegex.Matches(Text);
foreach (Match match in matches)
{
Text = Text.Replace(match.Value , string.Format("<a href=/"{0}/" target=/"_blank/">{1}</a>" , match.Value , match.Value));
}
//用正则表达式识别Email地址
Regex EmailRegex = new Regex(@"([a-zA-Z_0-9.-]+/@[a-zA-Z_0-9.-]+/./w+)" , RegexOptions.IgnoreCase | RegexOptions.Compiled);
matches = EmailRegex.Matches(Text);
foreach (Match match in matches)
{
Text = Text.Replace(match.Value , string.Format("<a href=mailto:{0}>{1}</a>" , match.Value , match.Value));
}
return Text;
}
二、调用方法则“自动”进行替换

div1.InnerHtml = Url_Rewrite(div1.InnerHtml);

//div1是div的ID号
//<div id="div1" runat="server"></div>

这样div中的Url或者E-mail只要符合正则表达式则会自动的转化成超级链接的格式。

如果页面比较多的时候,每个页面调用这个方法会比较麻烦,可以写在基类中,其他页面继承基类即可,但是我没有时间没有进行测试,也不知道是否可行,如果谁搞定了别忘记告诉我一下,谢谢!

 

本文地址:http://www.45fan.com/a/question/73463.html
Tags: URL ASP.NET 进行
编辑:路饭网
关于我们 | 联系我们 | 友情链接 | 网站地图 | Sitemap | App | 返回顶部