Based on your regex this could happen if the <img>
tag has no src attribute or if there are no <img>
tags at all.
As others have suggested you could fix this by checking $matches
first, but I'd like to suggest an alternate approach that may be more robust for parsing html in php, since using regex to do this is discouraged.
function get_first_image() {
global $post;
$first_img = '';
$dom = new DOMDocument();
$dom->loadHtml($post->post_content);
foreach ($dom->getElementsByTagName('img') as $img) {
if ($img->hasAttribute('src')) {
$first_image = $img->getAttribute('src');
break;
}
}
return $first_img;
}
The above function uses php's DOMDocument Class to iterate over <img>
tags and get the src attribute if it exists. (Note: I removed the ob_start()
and ob_end_clean()
functions from your code because I don't understand what purpose they were serving)