程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> 轉換html中的相對路徑成絕對路徑

轉換html中的相對路徑成絕對路徑

編輯:C#基礎知識
使用正則表達式轉換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//hovertree.com/";
String replacedHtml = ConvertRelativePathsToAbsolute(html, baseUrl);
// replacedHtml => <p><img src="http://hovertree.com/images/dot.gif" alt=\"test\" /></p> 
本文原文:http://hovertree.com/
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved