Skip to content

Instantly share code, notes, and snippets.

@ahutchings
Created January 24, 2009 04:26
Show Gist options
  • Save ahutchings/51332 to your computer and use it in GitHub Desktop.
Save ahutchings/51332 to your computer and use it in GitHub Desktop.
Embed Gists in (X)HTML without using document.write()
<?php
/**
* Replaces Gist javascript instances with their actual content,
* avoiding the use of document.write().
*
* @param string $source (X)HTML source
*
* @return string (X)HTML with embedded Gists
*/
function embed_gists($source)
{
$gists_regex = '/<script[^>]+src="(http:\/\/gist.github.com\/[^"]+)"[^>]*><\/script>/i';
preg_match_all($gists_regex, $source, $gists);
for ($i = 0, $n = count($gists[0]); $i < $n; $i++) {
$embed = file_get_contents($gists[1][$i]);
if ($embed != false) {
// remove document.writes
$embed = preg_replace('/document.write\(\'/i', '', $embed);
$embed = preg_replace('/(*ANYCRLF)\'\)$/m', '', $embed);
// remove javascript newlines
$embed = preg_replace('%(?<!/)\\\\n%', '', $embed);
// reverse javascript escaping
$embed = stripslashes($embed);
// remove line breaks
$embed = preg_replace("/[\n\r]/", '',$embed);
// replace the script tag
$source = str_replace($gists[0][$i], $embed, $source);
}
}
return $source;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment