2012-11-17 45 views
5

我有數組的字符串,我必須添加超鏈接到數組中的每個單項匹配項和給定的字符串。 主要是像維基百科中的東西。如何使用維基百科中的超鏈接以編程方式製作HTML文本?

喜歡的東西:

private static string AddHyperlinkToEveryMatchOfEveryItemInArrayAndString(string p, string[] arrayofstrings) 

{   } 

string p = "The Domesday Book records the manor of Greenwich as held by Bishop Odo ofBayeux; his lands were seized by the crown in 1082. A royal palace, or hunting lodge, hasexisted here since before 1300, when Edward I is known to have made offerings at the chapel of the Virgin Mary.";

arrayofstrings = {"Domesday book" , "Odo of Bayeux" , "Edward"}; 

returned string = @"The <a href = "#domesday book">Domesday Book</a> records the manor ofGreenwich as held by Bishop <a href = "#odo of bayeux">Odo of Bayeux</a>; his lands wereseized by the crown in 1082. A royal palace, or hunting lodge, has existed here sincebefore 1300, when <a href = "#edward">Edward<a/> I is known to have made offerings at thechapel of the Virgin Mary.";

什麼是這樣做的最佳方式?

+1

維基百科不會自動執行任何操作。你必須指定鏈接的位置,即使你可以做一個簡單的,特定的標記而不是完整的HTML。 – GolezTrol

回答

5

你也許可以很容易地做到這一點是這樣的:

foreach(string page in arrayofstrings) 
{ 
    p = Regex.Replace(
     p, 
     page, 
     "<a href = \"#" + page.ToLower() + "\">$0</a>", 
     RegexOptions.IgnoreCase 
    ); 
} 
return p; 

如果錨的資本可以是相同匹配的文本,你甚至可以擺脫的for循環:

return Regex.Replace(
    p, 
    String.Join("|", arrayofstrings), 
    "<a href = \"#$0\">$0</a>", 
    RegexOptions.IgnoreCase 
); 

現在模式變成,無論大小寫什麼都找到匹配,找到的任何內容都會放回到鏈接文本和href屬性中。

相關問題