We often allow users to enter a string of text on the webpage. However, when the content of the text contains angle brackets, single quotes, and HTML tags that are unique to some strings, it will be hard to handle, display of various mispositions, etc., because the user's input breaks the original tag structure during presentation.
In addition, when we enter line breaks and other special typographical symbols in the text, we cannot achieve the effect of line breaks when converting to HTML page content, the linefeed in the string does not work for HTML documents. At this time, we need to process the text to solve the above problems.
Directly to the Code:
Public class StringFilter
{
Public static string Clearstr (string inputString, int maxLength)
{
StringBuilder varstr = new StringBuilder ();
If (inputString! = Null) & (inputString! = String. Empty ))
{
If (inputString. Length> maxLength)
InputString = inputString. Substring (0, maxLength );
For (int I = 0; I <inputString. Length; I ++)
{
Switch (inputString [I])
{
Case '"':
Varstr. Append (""");
Break;
Case '<':
Varstr. Append ("<");
Break;
Case '> ':
Varstr. Append ("> ");
Break;
Case '\ N ':
Varstr. Append ("<br> ");
Break;
Case '':
Varstr. Append ("");
Break;
Case '&':
Varstr. Append ("&");
Break;
Default:
Varstr. Append (inputString [I]);
Break;
}
}
Varstr. Replace ("'","\"");
}
Return varstr. ToString ();
}
}
I hope you can give me some advice on the shortcomings.
For more information, see http://bbs.xiaoyuruanjian.com.