goranseric
1/18/2016 - 10:59 AM

Get all images in a HTML string

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;
}

?>