Quick actions

cmd+k|ctrl+k

Navigation

Languages

Get images from HTML img element in string

Snippet info

Language

Php

Visibility

public

Author

myles

Created

2016-11-14T00:46:48Z

Updated

2016-11-14T01:21:48Z

<?php

$data = 'alsdj<img src="http://localdomain.com/donotinclude.jpg">fklasjdf<img src="image.jpg">asdfasdf<img src="http://domain.com/image.jpg">asdfasdfsf<img src="dont_include_me.png">asdfasfasdf';
$images = array();

// Domains to not include images from (for instances where the full URL is specified to image)
$localhosts = array( 'localdomain.com' );
// Remove or add any extensions TO be included
$allowed_extensions = array( 'jpg', 'jpeg' );

preg_match_all('/(img|src)\=(\"|\')[^\"\'\>]+/i', $data, $media);
unset($data);
$data=preg_replace('/(img|src)(\"|\'|\=\"|\=\')(.*)/i',"$3",$media[0]);


foreach($data as $url)
{
    $url_data = parse_url( $url );
	$info = pathinfo($url);
	
	// Goto next, we're only looking for remote hosts
	if( ! array_key_exists( 'host', $url_data ) ) continue;
	
	// Check if this is an extension we want to include
	if( array_key_exists( 'extension', $info ) && in_array( $info['extension'], $allowed_extensions) ){
	    
	    // Verify this isn't one of our local hosts (where the full URL is specified)
	    if( ! in_array( $url_data['host'], $localhosts ) ){
	        array_push($images, $url);
	    }
	    
	}
	
}

echo 'Total Images: ' . count( $images );
// This is just linebreaks for display formatting
print "\n\n";
echo 'Image Data:';
var_dump( $images );
INFO