2009-08-03 43 views

回答

36
+2

此链接不再工作。这个类可以在这里找到http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringEscapeUtils.html和包含它的项目在这里http:// commons.apache.org/proper/commons-lang/ – Jakub 2013-06-07 12:58:55

+0

@Jakub谢谢。用较新的URL更新了帖子。 – Amber 2013-06-08 05:09:28

3

这就是通常所说的 “HTML转义”。我没有意识到标准库中的任何内容(尽管您可以通过使用XML转义来近似它)。但是,有很多第三方库可以做到这一点。来自org.apache.commons.lang的StringEscapeUtils有一个可以做到这一点的escapeHtml方法。

2
public static String stringToHTMLString(String string) { 
    StringBuffer sb = new StringBuffer(string.length()); 
    // true if last char was blank 
    boolean lastWasBlankChar = false; 
    int len = string.length(); 
    char c; 

    for (int i = 0; i < len; i++) 
     { 
     c = string.charAt(i); 
     if (c == ' ') { 
      // blank gets extra work, 
      // this solves the problem you get if you replace all 
      // blanks with &nbsp;, if you do that you loss 
      // word breaking 
      if (lastWasBlankChar) { 
       lastWasBlankChar = false; 
       sb.append("&nbsp;"); 
       } 
      else { 
       lastWasBlankChar = true; 
       sb.append(' '); 
       } 
      } 
     else { 
      lastWasBlankChar = false; 
      // 
      // HTML Special Chars 
      if (c == '"') 
       sb.append("&quot;"); 
      else if (c == '&') 
       sb.append("&amp;"); 
      else if (c == '<') 
       sb.append("&lt;"); 
      else if (c == '>') 
       sb.append("&gt;"); 
      else if (c == '\n') 
       // Handle Newline 
       sb.append("&lt;br/&gt;"); 
      else { 
       int ci = 0xffff & c; 
       if (ci < 160) 
        // nothing special only 7 Bit 
        sb.append(c); 
       else { 
        // Not 7 Bit use the unicode system 
        sb.append("&#"); 
        sb.append(new Integer(ci).toString()); 
        sb.append(';'); 
        } 
       } 
      } 
     } 
    return sb.toString(); 
}