【问题标题】:Creating link on HTML pages在 HTML 页面上创建链接
【发布时间】:2015-12-26 20:44:50
【问题描述】:

我有很多 HTML 页面,我想将段落的一些单词转换为链接。

例如:

string paragraph="Bookselling is the commercial trading of books, the retail and distribution end of the publishing process. The modern system of bookselling dates from soon after the introduction of printing.  Compare retail prices & arrival times on your books - all in one place. Select which books you want - used, digital, or rental"

string []Linkwords=new string[]{"books","Bookselling"};

我不知道我必须做什么,但这是我将其替换为链接的代码...

1- Sorting Linkwords ...
2- paragraph=paragraph.Replace(Linkwords[i],"<a href=\"#\">"+Linkwords[i]+"</a>");

它没有给出正确的答案

<a htef="#"><a htef="#">books</a>elling</a> is the commercial trading of <a htef="#">Books</a>

有没有现成的功能或者类似的东西。谢谢

【问题讨论】:

    标签: c# html tags


    【解决方案1】:

    我更喜欢将正则表达式用于高级搜索方法, 例如,您可以将代码替换为:

    using System;
    using System.Collections;
    using System.Text.RegularExpressions;
    
    public class Program
    {
        static void Main()
        {
            List<string> words   = new List<string> { @"\bbooks\b", @"\bbooksellings\b", ... };
            string pattern = string.Join("|", words.Select(w => Regex.Escape(w)));
            Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
        }
    }
    

    我把\b 的意思是单词边界,以确保选择的是一个单词而不是另一个单词的一部分。

    【讨论】:

    • 感谢您的关注
    【解决方案2】:

    这是因为 replace 首先匹配 booksales,然后用标签包装它,然后它匹配书籍并将其包装在另一个标签中。如果您首先匹配书籍,它会起作用,但是书籍销售永远不会起作用,同样,如果您匹配带有尾随空格的“书籍”,那么您将不会匹配以“书籍”结尾或其他字符结尾的句子。

    我会改用正则表达式进行搜索和替换,因为您可以检查完整的单词而不是特定的字符:

    var pattern = $"\\b{Linkwords.Join(@"\b|\b"}\\b"; // 用 \b|\b 作为分隔符连接单词
    段落 = Regex.Replace(段落, 模式, match => string.Concat(@"starting tag", match.Value, @"ending tag"))

    【讨论】:

    • 感谢您的关注
    猜你喜欢
    • 2018-07-31
    • 2011-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 2013-11-23
    • 2021-12-11
    相关资源
    最近更新 更多