Skip to content

Instantly share code, notes, and snippets.

@cahnory
Last active December 30, 2015 18:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cahnory/7870726 to your computer and use it in GitHub Desktop.
Save cahnory/7870726 to your computer and use it in GitHub Desktop.
HTML absolutizer
<?php
function absolutize($html, $base) {
// href, src, background attributes
$html = preg_replace('#(<[^>]+(href|src|background)=(?:3D)?")(?![a-z]+:)/?([^"]+)"#is', '$1'.$base.'$3"', $html);
// style attributes url(), src()
$html = preg_replace('#(<[^>]+style=(?:3D)?"[^"]*(url|src)\([\s\']*)(?![a-z]+:)/?([^)]+)\)#is', '$1'.$base.'$3)', $html);
// style tag
preg_match_all('#<style[^>]*>([^<]+)#is', $html, $styles);
foreach($styles[1] as $style){
$html = str_replace(
$style,
preg_replace('#((url|src)\([\s\']*)(?![a-z]+:)/?([^)]+)\)#is', '$1'.$base.'$3)', $style),
$html);
};
return $html;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment