/** * 字串編碼器類,將字串轉換為指定格式.<br> * <br> * 參數字典:<br> * src - source 來源的簡寫<br> * dst - destnation 目的的簡寫<br> * fnd - find 尋找的簡寫<br> * rep - replace 替換的簡寫<br> * idx - index 索引,下標的簡寫<br> * enc - encoding 編碼的簡寫<br> * <br> * 例子:<br> * <%=ArticleFormat.htmlTextEncoder(yourString)%> */public class StringEncoder{ /** * 將字串src中的子字串fnd全部替換為新子字串rep.<br> * 功能相當於java sdk 1.4的String.replaceAll方法.<br> * 不同之處在於尋找時不是使用Regex而是一般字元串. */ public static String replaceAll(String src, String fnd, String rep) throws Exception { if (src == null || src.equals("")) { return ""; } String dst = src; int idx = dst.indexOf(fnd); while (idx >= 0) { dst = dst.substring(0, idx) + rep + dst.substring(idx + fnd.length(), dst.length()); idx = dst.indexOf(fnd, idx + rep.length()); } return dst; } /** * 轉換為HTML編碼.<br> */ public static String htmlEncoder(String src) throws Exception { if (src == null || src.equals("")) { return ""; } String dst = src; dst = replaceAll(dst, "<", "<"); dst = replaceAll(dst, ">", "&rt;"); dst = replaceAll(dst, "/"", """); dst = replaceAll(dst, "'", "'"); dst = replaceAll(dst, " ", " "); dst = replaceAll(dst, "/r/n", "<br>"); dst = replaceAll(dst, "/r", "<br>"); dst = replaceAll(dst, "/n", "<br>"); return dst; }
/** * 轉換為XML編碼.<br> */ public static String xmlEncoder(String src) throws Exception { if (src == null || src.equals("")) { return ""; } String dst = src; dst = replaceAll(dst, "&", "&"); dst = replaceAll(dst, "<", "<"); dst = replaceAll(dst, ">", ">"); dst = replaceAll(dst, "/"", """); dst = replaceAll(dst, "/'", "´"); return dst; }} |