Skip to content

Instantly share code, notes, and snippets.

@asith-w
Created January 28, 2019 19:35
Show Gist options
  • Save asith-w/d96514a4ad9ac0d86792a1f2d1508da7 to your computer and use it in GitHub Desktop.
Save asith-w/d96514a4ad9ac0d86792a1f2d1508da7 to your computer and use it in GitHub Desktop.
replace .cs
public class HtmlHelper
{
string _attrib = string.Empty;
public string AddAttribute(string source, string tagName, string attrib)
{
_attrib = attrib;
string term = "<" + tagName + " [^>]+>";
Regex r = new Regex(term, RegexOptions.IgnoreCase);
MatchEvaluator myEvaluator = new MatchEvaluator(this.ProcessMatch);
return r.Replace(source, myEvaluator);
}
private string ProcessMatch(Match m)
{
string tag = m.Value;
if (tag.IndexOf(_attrib) == -1)
{
tag = tag.Replace(">", " " + _attrib + ">");
}
return tag;
}
public string ReplaceTag(string input, string oldTag, string newTag)
{
string pattern = @"(</?)"+oldTag+"([^>]*>)";
string replacement = "$1"+ newTag + "$2";
return Regex.Replace(input, pattern, replacement);
}
}
@asith-w
Copy link
Author

asith-w commented Jan 28, 2019

HtmlHelper helper = new HtmlHelper();
htmlText = helper.ReplaceTag(htmlText, "inline-image", "img");
htmlText = helper.AddAttribute(htmlText, "img", "src="_blank"");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment