Getting the first image in string with php

MHowey picture MHowey · Sep 20, 2011 · Viewed 33.8k times · Source

I'm trying to get the first image from each of my posts. This code below works great if I only have one image. But if I have more then one it gives me an image but not always the first.

I really only want the first image. A lot of times the second image is a next button

$texthtml = 'Who is Sara Bareilles on Sing Off<br>
<img alt="Sara" title="Sara" src="475993565.jpg"/><br>
<img alt="Sara" title="Sara two" src="475993434343434.jpg"/><br>';

preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $texthtml, $matches);
$first_img = $matches [1] [0];

now I can take this "$first_img" and stick it in front of the short description

<img alt="Sara" title="Sara" src="<?php echo $first_img;?>"/>

Answer

derp picture derp · Sep 20, 2011

If you only need the first source tag, preg_match should do instead of preg_match_all, does this work for you?

<?php
    $texthtml = 'Who is Sara Bareilles on Sing Off<br>
    <img alt="Sara" title="Sara" src="475993565.jpg"/><br>
    <img alt="Sara" title="Sara two" src="475993434343434.jpg"/><br>';
    preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $texthtml, $image);
    echo $image['src'];
?>