I'm using the following code in order to grab an image from a blog post:
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}
Now, I would need some help to introduce a minor modification. Here's what I'm looking for: I would like the code the ignore the first image, grab the second image it founds and, if it doesn't found a second image, use the default image (the fallback image).
I'm a big fan of the QueryPath project, which lets you work with HTML docs just like jQuery. Takes the grunt work out of such tasks. Give it a shot and let me know if that helps you out!
I second the answer @David gave you, but if you just need a quick and dirty fix you can do this:
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$content = preg_replace('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', '', $post->post_content, 1);
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}
The trick here is using preg_replace()
with the $limit
argument of 1 to delete the first image.