Skip to content

Instantly share code, notes, and snippets.

@themeblvd
Last active August 29, 2015 14:04
Show Gist options
  • Save themeblvd/0f2e3636f84d7db0f9cf to your computer and use it in GitHub Desktop.
Save themeblvd/0f2e3636f84d7db0f9cf to your computer and use it in GitHub Desktop.
<?php
/**
* Find all instances of image URL strings within
* a text block.
*/
function themeblvd_get_images( $str ) {
$protocols = array('http://', 'https://');
$extentions = array('.gif', '.jpeg', '.jpg', '.png');
$images = array();
foreach ( $protocols as $protocol ) {
foreach ( $extentions as $ext ) {
$pattern = sprintf( '/%s(.*?)%s/', preg_quote( $protocol, '/'), preg_quote( $ext, '/') );
preg_match_all( $pattern, $str, $img );
$images = array_merge( $images, $img[0] );
}
}
return $images;
}
// Example Usage:
$str = '
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.
http://mysite.com/images/test.jpg
<img src="http://mysite.com/images/test2.png" />
<a href="https://mysite.com/images/test3.gif">Hello World!</a>
';
$images = themeblvd_get_images( $str );
echo '<pre>'; print_r($images); echo '</pre>';
// Array
// (
// [0] => http://mysite.com/images/test.jpg
// [1] => http://mysite.com/images/test2.png
// [2] => https://mysite.com/images/test3.gif
// )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment