Skip to content

Instantly share code, notes, and snippets.

@xbansh33
Last active September 3, 2018 10:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xbansh33/527f08a94c434b4a39872e57a6017a4e to your computer and use it in GitHub Desktop.
Save xbansh33/527f08a94c434b4a39872e57a6017a4e to your computer and use it in GitHub Desktop.
function replace_images_with_embeds($html) // return all links within $html
{
$doc = new DOMDocument;
// This is a reasonable use of the @ operator as malformed HTML will produce
// a lot of warnings. Please don't shoot me ;)
@$doc->loadHTML($html, LIBXML_HTML_NODEFDTD);
// Get the links.
$links = $doc->getElementsByTagName('a');
$mod=false;
foreach ($links as $link) {
$href = $link->getAttribute('href');
$link_text = $link->nodeValue;
$ext = strtolower(substr($href, -4));
if ($ext == '.png' || $ext == '.jpg' || $ext == '.gif' || $ext == '.bmp')
{
//array_push($all_links,$this_link);
//$link->nodeValue = "<img src=\"test.jpg\">";
$link->nodeValue="";
$img_embed = $doc->createElement('img');
$img_embed->setAttribute('src',$href);
$link->appendChild($img_embed);
$mod=true;
}
}
if ($mod)
{
$return_html = $doc->saveHTML();
$return_html = str_replace("<html><body>","",$return_html);
$return_html = str_replace("</body></html>","",$return_html);
// prolly a better way to strip out the leading/trailing tags inserted by DOMDocument.
return $return_html;
}
else
return $html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment