在做B/S程序时我们多少会用到一点HTML特殊符号转译。 如:“&”——>“&” , "<"——>"<" , ">"——>">" , " "——>" " ...
符号转译成为编码:
/// <summary>
/// HTMLs the en code.
/// </summary>
/// <param name="sHTML">The HTML.</param>
/// <returns></returns>
public static string HTMLEnCode(string sHTML)
{
string sTemp = "";
if (sHTML.Length == )
{
return "";
}
sTemp = sHTML.Replace("<", "<");
sTemp = sTemp.Replace("&", "&");
sTemp = sTemp.Replace(">", ">");
sTemp = sTemp.Replace("'", "'");
sTemp = sTemp.Replace(" ", " ");
sTemp = sTemp.Replace("\"", """);
sTemp = sTemp.Replace("\n", "<br />");
return sTemp;
}
当我们需要再转换成HTML代码的时候会用到:
/// <summary>
/// HTMLs the de code.
/// </summary>
/// <param name="sHTML">The HTML.</param>
/// <returns></returns>
public static string HTMLDeCode(string sHTML)
{
string sTemp = "";
if (sHTML.Length == )
{
return "";
}
sTemp = sHTML.Replace("<", "<");
sTemp = sTemp.Replace(">", ">");
sTemp = sTemp.Replace("'", "'");
sTemp = sTemp.Replace(" ", " ");
sTemp = sTemp.Replace(""", "\"");
sTemp = sTemp.Replace("&", "&");
sTemp = sTemp.Replace("<br />", "\n");
return sTemp;
}
但是我们往往会忽略最重要的一点, 就是当我们把转译符转换成HTML的时候需要注意一下转码的顺序,我们必须在 “<”, ">", " " , "'" ,"\" 这几个符号转译之后最后在转换 “&”符, 不然,转译过后的&后面如果跟有 “nbsp;”这样连续的字符的时候就会重新转换成为了空格。
不积跬步,无以至千里;不积小流,无以成江海。只是在于积累,希望这点发现也可以帮到你!