用于在博客文章中抓取第二个图像的PHP代码


PHP Code for grabbing second image on 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;
}

现在,我需要一些帮助来引入一个小修改。这是我正在寻找的:我想要的代码忽略第一个图像,抓住它找到的第二个图像,如果它没有找到第二个图像,使用默认图像(后备图像)。

我是QueryPath项目的忠实粉丝,它允许您像jQuery一样使用HTML文档。把繁重的工作从这样的任务中解脱出来。试试吧,如果这对你有帮助,请告诉我!

我同意@David给你的答案,但如果你只是需要一个快速而肮脏的修复,你可以这样做:

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;
}

这里的技巧是使用preg_replace()$limit参数为1来删除第一张图像。