在 HTML 个页面上创建 link

Creating link on HTML pages

我有很多 HTML 页,我想将某些段落的文字转换为 link。

例如:

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"};

我不知道我必须做什么,但这是我将其替换为 link...

的代码
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>

是否有现成的函数或类似的东西that.thanks

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

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意思词边界,以确保选择的是一个词而不是另一个词的一部分。

这是因为 replace 首先匹配 bookselling,然后用标签包装它,然后它匹配书籍并将其包装在另一个标签中。如果您先匹配书籍,它会起作用,但随后书籍销售将永远不起作用,同样,如果您将 "books " 与尾随 space 匹配,那么您将不会匹配以 [=19= 结尾的句子] 或尾随其他字符。

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

var pattern = $"\b{Linkwords.Join(@"\b|\b"}\b"; // joins the words with \b|\b as a separator
paragraph = Regex.Replace(paragraph, pattern, match => string.Concat(@"starting tag", match.Value, @"ending tag"))