将字符串转换为html(超链接)

Meh*_*Man 3 c#

我为字符串类定义了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

rob*_*sta 5

看到这一个,使用正则表达式

private string ConvertUrlsToLinks(string msg) {
    string regex = @"((www\.|(http|https|ftp|news|file)+\:\/\/)[&#95;.a-z0-9-]+\.[a-z0-9\/&#95;:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
    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=\"&#95;blank\">$1</a>").Replace("href=\"www", "href=\"http://www");
}
Run Code Online (Sandbox Code Playgroud)