I have had a problem with encoding in a project when trying to convert certain html code into image format. It happens when we receive html that has certain characters with accents and other non standard ones.
To combat this I have the following method which finds all of the text inside html tags and then converts all of it (that aren't already in the encoded format i.e.
) to their html escaped representation i.e. +
to +
.
private string EncodeToHtml(string contents)
{
Regex textRegex = new Regex("(?<!<[^>]*)(?<Text>[^<>]*)", RegexOptions.Compiled);
Regex innerRegex = new Regex("(?<=^|;)([^&]|&(?=[^&;]*(?:&|$)))+", RegexOptions.Compiled);
return textRegex.Replace(contents, new MatchEvaluator(m =>
{
return innerRegex.Replace(m.Groups["Text"].Value, new MatchEvaluator(m2 =>
{
string result = string.Empty;
foreach (char c in m2.Value)
{
result += $"&#{(int)c};";
}
return result;
}));
}));
}
I'd appreciate any comments on the code especially anyway to make it more efficient.
å
are considered valid html and so aren't escaped using that method (I think I originally tried theWebUtility
version from .NET 4.0 but it should have the same affect). That is why I rolled my own solution, it's not that it is invalid html, its that it causes problems for another part of my application. \$\endgroup\$