/***************************************************************************
* This function assumes string - html as a first argument,
* array allowed tags as a second argument and clear
* all tags different than tags in the array. Also prevent XSS atacks -
* clear all JavaScript events and style attributes.
* Example:
* filterTags("<br><i> ahssh </i><img style='alabala' onload='alert1'>",
* new string[] {"br","ul","span"});
* this will return "<br> ahssh "
* @author Georgi Naumov
* @date 17.01.2011
* gonaumov@gmail.com for contacts and suggestions.
***************************************************************************/
protected string filterTags(string htmlString, string[] allowedTags)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
string buffer;
string styleAndEventPattern = "(?:style|on[a-z]+)=(?:\"|')?[^>]+(?:\"|')?(?=[^>]*>)";
for (int i = 0; i < allowedTags.Length; i++)
{
if (i == 0)
{
sb.Append("<(?!(?:\\s*/?\\b").Append(allowedTags[i]).Append("\\b)");
}
else
{
sb.Append("|(?:\\s*/?\\b").Append(allowedTags[i]).Append("\\b)");
}
}
sb.Append(")[^>]*>");
buffer = Regex.Replace(htmlString, sb.ToString(), "", RegexOptions.IgnoreCase);
return Regex.Replace(buffer, styleAndEventPattern, "", RegexOptions.IgnoreCase);
}
* This function assumes string - html as a first argument,
* array allowed tags as a second argument and clear
* all tags different than tags in the array. Also prevent XSS atacks -
* clear all JavaScript events and style attributes.
* Example:
* filterTags("<br><i> ahssh </i><img style='alabala' onload='alert1'>",
* new string[] {"br","ul","span"});
* this will return "<br> ahssh "
* @author Georgi Naumov
* @date 17.01.2011
* gonaumov@gmail.com for contacts and suggestions.
***************************************************************************/
protected string filterTags(string htmlString, string[] allowedTags)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
string buffer;
string styleAndEventPattern = "(?:style|on[a-z]+)=(?:\"|')?[^>]+(?:\"|')?(?=[^>]*>)";
for (int i = 0; i < allowedTags.Length; i++)
{
if (i == 0)
{
sb.Append("<(?!(?:\\s*/?\\b").Append(allowedTags[i]).Append("\\b)");
}
else
{
sb.Append("|(?:\\s*/?\\b").Append(allowedTags[i]).Append("\\b)");
}
}
sb.Append(")[^>]*>");
buffer = Regex.Replace(htmlString, sb.ToString(), "", RegexOptions.IgnoreCase);
return Regex.Replace(buffer, styleAndEventPattern, "", RegexOptions.IgnoreCase);
}
Няма коментари:
Публикуване на коментар