1

Basically a dup of this question using php, but I need it for C#.

I need to be able to replace any & that is not currently not any HTML entity (e.g. &) before outputting to screen. I was thinking a regex, but I'm not sure if .Net has something built in that will do this.

3
  • So you have a string with mixed HTML and non-HTML text? You should go closer to the source and clean it up before it gets mixed up in the string in the first place. Commented Apr 27, 2010 at 17:29
  • Ya, I'm trying to get a quick fix to solve a problem in which I can then come back and fix the real problem which deals with how the string is being made. Fixing the real problem is going to take some time though. Commented Apr 27, 2010 at 17:32
  • I've created the a function to encode & and ' without messing up with already encoded & or ' or " . Check the following link http://stackoverflow.com/a/21317732/2123134 Commented Jan 23, 2014 at 19:40

3 Answers 3

2

You can use HttpUtility.HtmlEncode.
Whithing the context of a page or UserControl, you can use Server.HtmlEncode.

Sign up to request clarification or add additional context in comments.

Comments

2

Better AntiXss.HtmlEncode, prevents XSS.

Comments

1

You could always HTML Decode the string (which would turn any HTML symbols into their display equivalents), replace any &'s, and then Encode the string again (which turns the symbols back into what they were originally). You might need to watch for side effects though.

5 Comments

Wouldn't that get rid of ampersands that were encoded by &?
Yup - which is why you would want to test this solution a bit. My response to that issue would be to replace & with some special symbol unlikely to be used (like (char)1), decode, replace, encode, and then replace (char)1 with &.
in your example why not just replace all & with & then all & with & Why bother with another string
Seems like a decode/encode cycle would take care of it without having to replace amperstands. Decode would transform already encoded characters back to plain text, and encoding would reverse it while also handling characters that weren't properly encoded before.
@cory, your idea would make " => "

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.