看到jk_10000在javascript区提供了此代码,就顺路牵来。
当然,碰到我这个代码格式化狂人,是肯定要面目全非的,啊哈哈哈哈哈哈......
htmltextencoder方法将文本格式转换为html格式。
xmlencoder方法将文本格式转换为xml格式。
/**
* 字符串编码器类,将字符串转换为指定格式.<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>
* 不同之处在于查找时不是使用正则表达式而是普通字符串.
*/
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, "", "'");
return dst;
}
/**
* 转换为html文字编码.<br>
*/
public static string htmltextencoder(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;
}
/**
* 转换为url编码.<br>
*/
public static string urlencoder(string src, string enc) throws exception
{
return java.net.urlencoder.encode(src, enc) ;
}
/**
* 转换为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;
}
/**
* 转换为sql编码.<br>
*/
public static string sqlencoder(string src) throws exception
{
if (src == null || src.equals(""))
{
return "";
}
return replaceall(src, "", "");
}
/**
* 转换为javascript编码.<br>
*/
public static string jsencoder(string src) throws exception
{
if (src == null || src.equals(""))
{
return "";
}
string dst = src;
dst = replaceall(dst, "", "\\");
dst = replaceall(dst, "\"", "\\\"");
//dst = replaceall(dst, "\r\n", "\\\n"); // 和\n转换有冲突
dst = replaceall(dst, "\n", "\\\n");
dst = replaceall(dst, "\r", "\\\n");
return dst;
}
}
文章整理:站长天空 网址:http://www.z6688.com/
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!




