Skip to content

Instantly share code, notes, and snippets.

@GoldenEra
Last active August 29, 2015 14:20
Show Gist options
  • Save GoldenEra/1fe7568383716eb90533 to your computer and use it in GitHub Desktop.
Save GoldenEra/1fe7568383716eb90533 to your computer and use it in GitHub Desktop.
php:get the imag's src and alt from a html
/**
* get src of the first img tag from string
* @param [type] string
* @param [type] boolean if true get all the images' src
* @return [type] first src or none
*/
function get_img_src($str, $isAll = false){
preg_match('/\<img.*src=\"(.*?)\"/i',$str,$src);
preg_match('/alt\s*=\"(.*?)\"/i',$str,$alt);
if ($isAll) {
preg_match_all('/\<img.*src=\"(.*?)\"/i',$str,$src);
preg_match_all('/alt\s*=\"(.*?)\"/i',$str,$alt);
}
$result = false;
if($src[1]) {
$img = array(
"url" => $src[1],
"alt" => $alt[1]
);
if ($isAll) {
$img = array_map(function($src, $alt){
return array( 'url' => $src, 'alt' => $alt);
}, $src[1], $alt[1]);
}
$result = $img;
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment