Skip to content

Instantly share code, notes, and snippets.

@joshuabaker
Last active May 11, 2022 07:17
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save joshuabaker/313648 to your computer and use it in GitHub Desktop.
Save joshuabaker/313648 to your computer and use it in GitHub Desktop.
Get all images in a HTML string
<?php
/**
* Returns all img tags in a HTML string with the option to include img tag attributes
*
* @author Joshua Baker
*
* @example $post_images[0]->html = <img src="example.jpg">
* $post_images[0]->attr->width = 500
*
* @param $html_string string The HTML string
* @param $get_attrs boolean If TRUE all of the img tag attributes will be returned
* @return $post_images array An array of objects
*/
function get_images($html_string, $get_attrs = FALSE)
{
$post_images = array();
// Get all images
preg_match_all('/<img [^>]+>/', $html_string, $image_matches, PREG_SET_ORDER);
// Loop the images and add the raw img html tag to $post_images
foreach ($image_matches as $image_match)
{
$post_image->html = $image_match[0];
// If attributes have been requested get them and add them to the $post_image
if ($get_attrs == TRUE)
{
preg_match_all('/\s+?(.+)="([^"]*)"/U', $image_match[0], $image_attr_matches, PREG_SET_ORDER);
foreach ($image_attr_matches as $image_attr)
{
$post_image->attr->{$image_attr[1]} = $image_attr[2];
}
}
$post_images[] = $post_image;
}
return $post_images;
}
?>
@ivan-khuda
Copy link

ivan-khuda commented Jun 23, 2021

Please change first reg exp to
preg_match_all('/<img [^>]+>/', $html_string, $image_matches, PREG_SET_ORDER);

Because reg exp that you have does not work if string have multiple images

@joshuabaker
Copy link
Author

Thanks, @ivan-khuda. 👍

I wrote this over a decade ago. I’d suggest looking at DOMDocument or similar instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment