-
-
Save slaffko1/ffa4faa401665b371bc8ffc9a42528b9 to your computer and use it in GitHub Desktop.
Get all images in a HTML string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment