Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Created July 9, 2019 12:55
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 tommcfarlin/35581dce7a46c4a78f5168d0291aa961 to your computer and use it in GitHub Desktop.
Save tommcfarlin/35581dce7a46c4a78f5168d0291aa961 to your computer and use it in GitHub Desktop.
[PHP] Remove Images with DOMDocument
<?php
// Instantiate a DOMDocument object and load the incoming $description HTML.
$domDocument = new DOMDocument();
$domContent = $domDocument->loadHTML(mb_convert_encoding($description, 'HTML-ENTITIES'));
// Find all of the images in the HTML.
$images = $domDocument->getElementsByTagName('img');
// If there are images, then iterate through each of them.
if (0 !== \count($images)) {
$urlPrefix = $this->getUrlPrefix(); // A helper function for getting the URL prefix.
foreach ($images as $image) {
$image->setAttribute(
'src',
$urlPrefix.$image->getAttribute('src')
);
// If the image's source results in a 404 status code, set the `src` to an empty string.
if (!$this->isValidImage($image->getAttribute('src'))) {
$image->setAttribute('src', '');
}
}
}
// Save the changed document and send it to the front-end.
return $domDocument->saveHTML();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment