Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make programmatically html text with hyperlinks like in Wikipedia?

Tags:

string

c#

regex

I have array of strings and I have to add hyperlink to every single match of item in array and given string. Principally something like in Wikipedia.

Something like:

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

{            }

string p = "The Domesday Book records the manor of Greenwich as held by Bishop Odo of Bayeux; his lands were seized by the crown in 1082. A royal palace, or hunting lodge, has existed 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 of Greenwich as held by Bishop <a href = "#odo of bayeux">Odo of Bayeux</a>; his lands were seized by the crown in 1082. A royal palace, or hunting lodge, has existed here since before 1300, when <a href = "#edward">Edward<a/> I is known to have made offerings at the chapel of the Virgin Mary.";

What is the best way of doing that?

like image 369
Mikaèl Avatar asked Nov 17 '12 21:11

Mikaèl


1 Answers

You could probably quite easily do it like this:

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

If the capitalization of the anchor can be the same as the matched text, you can even get rid of the for-loop:

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

Now the pattern becomes Domesday book|Odo of Bayeux|Edward, matches are found regardless of capitalization, and whatever is found is put back both into the link text and into the href attribute.

like image 185
Martin Ender Avatar answered Oct 13 '22 00:10

Martin Ender