將文字格式設定的文章轉換為html/xml格式文本的功能封裝到Javabean

來源:互聯網
上載者:User
在將textarea裡面的大段文字儲存到資料庫,然後提取出來以顯示時,格式無效,因為此時是html格式,所以需要轉換。

看到JK_10000在javascript區提供了此代碼,就順路牽來。
當然,碰到我這個代碼格式化狂人,是肯定要面目全非的,啊哈哈哈哈哈哈......

/** * 字串編碼器類,將字串轉換為指定格式.<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, "<", "&lt;"); dst = replaceAll(dst, ">", "&rt;"); dst = replaceAll(dst, "/"", "&quot;"); dst = replaceAll(dst, "'", "&#039;"); dst = replaceAll(dst, " ", "&nbsp;"); 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, "&", "&amp;"); dst = replaceAll(dst, "<", "&lt;"); dst = replaceAll(dst, ">", "&gt;"); dst = replaceAll(dst, "/"", "&quot;"); dst = replaceAll(dst, "/'", "&acute;"); return dst; }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.