在HTML页面上创建链接

本文关键字:创建 链接 HTML | 更新日期: 2023-09-27 18:28:03

我有很多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>

有现成的功能吗?谢谢

在HTML页面上创建链接

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

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首先匹配图书销售,然后用标签包装,然后匹配图书并将其包装在另一个标签中。如果你先匹配书籍,这会起作用,但之后图书销售就永远不会起作用,同样,如果你匹配带有尾随空格的"books",那么你就不会匹配以"books"或其他字符尾随的句子

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

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