Convert Relative Paths to Absolute Using Regular Expressions

Convert Relative Paths to Absolute Using Regular Expressions

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);
}

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> 
Labels: C#, Regular Expressions 
This entry was posted in Code Snippets. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s