2009-08-03 5 views

답변

36

StringEscapeUtils에 문자열

"<Hello>" 

을 변경하면이를 위해 정확하게 설계된 기능이 있습니다

일반적으로 "HTML 탈출"라고

http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringEscapeUtils.html

+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

+0

@ Jakub Thanks. 게시물을 최신 URL로 업데이트했습니다. – Amber

3

. 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(); 
} 
+0

유니 코드 보조 문자는 문자열에서 2 개의 문자로 인코딩되며 올바르게 렌더링되지 않습니다. 유니 코드를 지원하려면 문자가 아닌 코드 포인트를 처리해야합니다. – Jakub

+1

안녕하세요, 이건 오래된 q입니다.하지만 궁금한 점이 있습니다. 문자 하나 하나씩 처리하는 대신 String.replaceAll() 메서드가 작동하지 않는 이유는 무엇입니까? –

관련 문제