Get first image from content

The following functions are useful especially when pull an rss feed from a remote site, and you want to display the first image in the post. returnImage() will return the first entire image tag, which can then be passed to scrapeImage to return just the image source.

// returns the first image from the passed in text
function returnImage ($text) {
    $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
    $pattern = "/<img[^>]+\>/i";
    preg_match($pattern, $text, $matches);
    $text = $matches[0];
    return $text;
}

// strips out the image src from an img tag
function scrapeImage($text) {
    $pattern = '/src=[\'"]?([^\'" >]+)[\'" >]/';
    preg_match($pattern, $text, $link);
    $link = $link[1];
    $link = urldecode($link);
    return $link;
}
 
Scroll to Top