使用正则表达式转换html中的相对路径到决定路径

Convert Relative Paths to Absolute Using Regular Expressions

I ran into a situation where I needed to screen scrape some content from a site and display it on my own site. This works really well except for dependent files like javascripts, SWFs and images that had src attributes with relative paths. So I figured it wouldn't be that hard to create a helper method to find and replace them using Regular Expressions. So here it is:

public static String ConvertRelativePathsToAbsolute(String text, String absoluteUrl)
{
String value = Regex.Replace(text,
"<(.*?)(src|href)=\"(?!http)(.*?)\"(.*?)>",
"<$1$2=\"" + absoluteUrl + "$3\"$4>",
RegexOptions.IgnoreCase | RegexOptions.Multiline);
// Now just make sure that there isn't a // because if
// the original relative path started with a / then the
// replacement above would create a //.
return value.Replace(absoluteUrl + "/", absoluteUrl);
}

Sample Usage:

String html = "<p><img src=\"images/dot.gif\" alt=\"test\" /></p>";
String baseUrl = "http//www.nontalk.com/";
String replacedHtml = ConvertRelativePathsToAbsolute(html, baseUrl);
// replacedHtml => <p><img src="http://www.nontalk.com/images/dot.gif" alt=\"test\" /></p> 
本文原文:http://code.nontalk.com/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值