Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

encode html in Asp.net C# but leave tags intact

Tags:

c#

html-encode

I need to encode a whole text while leaving the < and > intact.

example

<p>Give me 100.000 €!</p>

must become:

<p>Give me 100.000 &euro;!</p>

the html tags must remain intact

like image 401
MichaelD Avatar asked Dec 02 '25 21:12

MichaelD


1 Answers

Use a regular expression that matches either a tag or what's between tags, and encode what's between:

html = Regex.Replace(
  html,
  "(<[^>]+>|[^<]+)",
  m => m.Value.StartsWith("<") ? m.Value : HttpUtility.HtmlEncode(m.Value)
);
like image 72
Guffa Avatar answered Dec 04 '25 09:12

Guffa