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;?>"/>
If you only need the first source tag,
preg_match
should do instead ofpreg_match_all
, does this work for you?Don't use regex to parse html. Use an html-parsing lib/class, as phpquery:
Download: http://code.google.com/p/phpquery/
After testing an answer from here Using regular expressions to extract the first image source from html codes? I got better results with less broken link images than the answer provided here.
For more consistent results use this object http://simplehtmldom.sourceforge.net/ which allows you to manipulate html. An example is provided in the response in the first link I posted.
Enjoy
Are you sure the regex is always matching the first one? Try printing the array each time you call it to see:
error_log(var_export($matches, true));