我为字符串类定义了 ToHtml() 扩展并将中断转换为 <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/>");
}
}
c#、asp.net
最佳答案
see this one , 使用正则表达式
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");
}
关于c# - 将字符串转换为 html(超链接),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8386735/