본문 바로가기

Programming/java

[java] HTML 특수문자 처리

HTML 특수문자 처리



1. &amp 에서 & 형태로 변환

public static String toTEXT(String str) {

if(str == null)

return null;


String returnStr = str;

returnStr = returnStr.replaceAll("<br>", "\n");

returnStr = returnStr.replaceAll("&gt;", ">");

returnStr = returnStr.replaceAll("&lt;", "<");

returnStr = returnStr.replaceAll("&quot;", "\"");

returnStr = returnStr.replaceAll("&nbsp;", " ");

returnStr = returnStr.replaceAll("&amp;", "&");

returnStr = returnStr.replaceAll("\"", "&#34;");

// returnStr = returnStr.replaceAll("&#34;", "\"");


return returnStr;

}



2. &에서 &amp 형태로 변환

public static String getSpclStrCnvr(String srcString) {

String rtnStr = null;

try{

StringBuffer strTxt = new StringBuffer("");

char chrBuff;

int len = srcString.length();


for(int i = 0; i < len; i++) {

chrBuff = (char)srcString.charAt(i);


switch(chrBuff) {

case '<':

strTxt.append("&lt;");

break;

case '>':

strTxt.append("&gt;");

break;

case '&':

strTxt.append("&amp;");

break;

default:

strTxt.append(chrBuff);

}

}


rtnStr = strTxt.toString();


}catch(Exception e) {

e.printStackTrace();

}


return rtnStr;

}