2009-08-03 44 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(); 
}