最代码官方
2016-07-19 13:42:14
证
一段很实用的替换html字符串中所有A标签属性href为网站跳转链接的java正则代码
最近为了优化seo,将站内所有外站的链接都替换为http://www.zuidaima.com/link.htm?url=http%3A%2F%2Fwww.baidu.com等的链接。所以经过n次测试编写如下方法:
比如原html:
<a href="http://stackoverflow.com/questions/10509699/must-issue-a-starttls-command-first" target="_blank">http://stackoverflow.com/questions/10509699/must-issue-a-starttls-command-first</a>
替换为:
<a href="http://www.zuidaima.com/link.htm?url=http%3A%2F%2Fstackoverflow.com%2Fquestions%2F10509699%2Fmust-issue-a-starttls-command-first" target="_blank">http://stackoverflow.com/questions/10509699/must-issue-a-starttls-command-first</a>
//将href外站的链接换为302跳转
public static String formatA(String value) {
if (value == null)
throw new NullArgumentException("html input");
//html的标签属性肯定是以单引号或双引号包含
String pattern = "<a([\\w\\W]*?) href=['|\"]([\\w\\W]*?)['|\"]([\\w\\W]*?)>";
Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(value);
while (m.find()) {
String a = m.group();
//本站内部链接不处理
if (a.contains("javaniu")
|| a.contains("zuidaima") || a.contains("javascript:void")
|| a.matches("href=['|\"]?\\/")) {
continue;
}
String _url = m.group(2);
String url = _url;
try {
url = URLEncoder.encode(_url, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
url = String.format(GlobalConstants.URL_LINK, url);
//将target属性替换为"",以便所有外链都是_blank打开
String targetReg = "target=['|\"].*?['|\"']";
String prefix = m.group(1).replaceAll(targetReg, "");
String suffix = m.group(3).replaceAll(targetReg, "");
//整段匹配不会出现错误
String _a = "<a" + prefix + " href='" + url + "'" + suffix + " target='_blank'>";
value = value.replace(a, _a);
}
return value;
}
其中
public static final String URL_LINK = DOMAIN + "link.htm?url=%s";
是最代码线上已经成功测试并运行的代码片段,牛牛们可以参考下
猜你喜欢
请下载代码后再发表评论
相关代码
最近下载
最近浏览
浪里格朗 LV4
2023年1月31日
moomin709 LV24
2022年8月13日
微信网友_5793263879983104 LV1
2022年1月17日
wh55556 LV2
2021年11月9日
月之氏族 LV23
2019年11月6日
大度嘟嘟 LV2
2019年9月24日
candidcrat LV1
2019年6月6日
zhangyingrui LV2
2019年3月14日
tsmjdk LV3
2019年2月20日
353249573 LV9
2019年2月9日




