【问题标题】:Create Html links from in-text Urls using Html Agility Pack使用 Html Agility Pack 从文本内 URL 创建 Html 链接
【发布时间】:2013-03-20 14:51:50
【问题描述】:

如何使用 Html Agility Pack + c# 将文本中的 url 转换为 html 链接?

例如:“www.stackoverflow.com 是一个非常酷的网站。”

输出:

"<a href="www.stackoverflow.com">www.stackoverflow.com</a>  is a very cool site."

【问题讨论】:

  • 你有没有尝试过?先展示你的努力..
  • 我尝试过使用正则表达式并且它可以工作,但如果它可以做到这一点,我想尝试 Html Agility 包。我对使用 Html Agility 包进行了大量研究,但尚未找到任何解决方案。
  • Html Agility Pack 适用于 HTML 字符串。您提供的字符串不是完整的 HTML 片段。另外,在您的示例中引号是否重要/重要?一段真正的 c# 代码会有所帮助。
  • 我们能不能避免把它变成一个 cmets 链。如果我正在努力实现我所知道的 Html 敏捷包,我会提供这段代码。我想要的只是是否有人尝试过这个并且可以确认它是否可能。为什么要为@SonerGönül +1?

标签: c# html-agility-pack


【解决方案1】:

感谢@user1778606 的回答。尽管它仍然使用了一些正则表达式,但我得到了这个工作。它工作得更好、更安全(即它永远不会在超链接和 href 属性中创建超链接)。

        //convert text to html
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(inputString);

        // \w* - means it can start with any alphanumeric charactar
        // \s+ - was placed to replace all white spaces (when there is more than one word).
        // \b - set bounderies for the keyword
        const string pattern = @"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[.\!\/\\w]*))?)";

        //get all elements text propery except for anchor element 
        var nodes = doc.DocumentNode.SelectNodes("//text()[not(ancestor::a)]") ?? new HtmlAgilityPack.HtmlNodeCollection(null);

        foreach (var node in nodes)
        {
            Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
            node.InnerHtml = regex.Replace(node.InnerHtml, "<a href=\"$1\">$1</a>").Replace("href=\"www", "href=\"http://www");
        }

        return doc.DocumentNode.OuterHtml;

【讨论】:

    【解决方案2】:

    我很确定这是可能的,虽然我没有尝试过。

    以下是如何用链接替换文档中的固定字符串

    Find keyword in text when keyword match certain conditions - C#

    以下是如何为 url 进行正则表达式

    regular expression for url

    把这些放在一起应该是可能的。

    伪代码

    选择所有文本节点

    对于每个节点

    获取内部文本
    在文本中查找 url(使用正则表达式?)
    对于找到的每个网址

    用字符串文字链接标签(a href = etc ...)替换url的文本

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-13
      • 2021-07-31
      • 1970-01-01
      • 2011-10-14
      • 2011-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多