PHP Get First Image (PGFI)

I am trying to get the first image from each of my posts. The code below works fine if I only have one image. But if I have more than one, it gives me the images but not always the first one.

I really just want the first image. Most of the time the second image is the 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 paste it in front of the short description

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

Solutip

If you only need the first source tag,  preg_match it's better to do this instead of  preg_match_all, is this right 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'];
?>

Post a Comment

Previous Next

نموذج الاتصال