我为字符串类定义了ToHtml()扩展并将break转换为<br/>.如何检测超链接并转换为<a>元素?
public static class StringExtension
{
public static string ToHtml(this string item)
{
//\r\n windows
//\n unix
//\r mac os
return item.Replace("\r\n", "<br/>").Replace("\n", "<br/>").Replace("\r", "<br/>");
}
}
Run Code Online (Sandbox Code Playgroud)
c#,asp.net
看到这一个,使用正则表达式
private string ConvertUrlsToLinks(string msg) {
string regex = @"((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
Regex r = new Regex(regex, RegexOptions.IgnoreCase);
return r.Replace(msg, "<a href=\"$1\" title=\"Click to open in a new window or tab\" target=\"_blank\">$1</a>").Replace("href=\"www", "href=\"http://www");
}
Run Code Online (Sandbox Code Playgroud)