您的位置:首页 > Web前端 > HTML

处理文章截取有html脚本的问题

2010-10-21 15:09 344 查看
package people.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.jsp.tagext.TagSupport;

public class CutHtml extends TagSupport {

private static String htmlMatch = "";

public static String removeMatchHtmlTag() {

Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>(.*?)<///1>");
Matcher m = p.matcher(htmlMatch);

if (m.find()) {

htmlMatch = htmlMatch.replaceAll("<([a-zA-Z]+)[^<>]*>(.*?)<///1>", "$2");

removeMatchHtmlTag();
}

return htmlMatch;
}

public static String subStringHTML(String param, int length, String endWith) {

if (length < 1) {

return null;
}

if (param.length() < length) {
return param;
}

StringBuffer result = new StringBuffer();
StringBuffer str = new StringBuffer();
int n = 0;

char temp;

boolean isCode = false;
boolean isHTML = false;
for (int i = 0; i < param.length(); i++) {
temp = param.charAt(i);
if (temp == '<') {
isCode = true;
} else if (temp == '&') {
isHTML = true;
} else if (temp == '>' && isCode) {
n = n - 1;
isCode = false;
} else if (temp == ';' && isHTML) {
isHTML = false;
}
if (!isCode && !isHTML) {
n = n + 1;
if ((temp + "").getBytes().length > 1) {
n = n + 1;
}
str.append(temp);
}
result.append(temp);
if (n >= length) {
break;
}
}

result.append(endWith);

String temp_result = result.toString().replaceAll("(>)[^<>]*(<?)", "$1$2");

temp_result = temp_result
.replaceAll(
"<(AREA|BASE|BASEFONT|BODY|BR|COL|COLGROUP|DD|DT|FRAME|HEAD|HR|HTML|IMG|INPUT|ISINDEX|LI|LINK|META|OPTION|P|PARAM|TBODY|TD|TFOOT|TH|THEAD|TR|area|base|basefont|body|br|col|colgroup|dd|dt|frame|head|hr|html|img|input|isindex|li|link|meta|option|p|param|tbody|td|tfoot|th|thead|tr)[^<>]*/>",
"");

htmlMatch = temp_result;
temp_result = removeMatchHtmlTag();

Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>");
Matcher m = p.matcher(temp_result);
List<String> endHTML = new ArrayList<String>();

while (m.find()) {
endHTML.add(m.group(1));
}

for (int i = endHTML.size() - 1; i >= 0; i--) {
result.append("</");
result.append(endHTML.get(i));
result.append(">");
}
return result.toString();

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐