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

标签 c#

我为字符串类定义了 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)+\:\/\/)[&#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");
}

关于c# - 将字符串转换为 html(超链接),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8386735/

相关文章:

c# - 如果在 C# 中该窗体发生异常,如何优雅地关闭该窗体

c# - Fluent Validation - 当特定验证失败时停止验证所有其他验证

带有 Windows 窗体应用程序的 C# 套接字服务器

c# - 自定义 API Controller 总是返回 404 not found

c# - 如何在 WPF 中保持可缩放、可滚动内容的纵横比?

c# - 需要解决方法 : notify a user that exe is missing dependencies from within the application?

c# - 跨多个 Windows 10 虚拟桌面的持久窗口?

c# - 使用 LINQ 删除字典中的重复项和这些重复项的计数

c# - 生成操作 : Content - how do get it to the Executing Assemblies folder instead of just the project folder?

javascript - 如何知道 CRM 2016 中的插件何时结束?