微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

用于在博客文章上获取第二张图片的PHP代码

如何解决用于在博客文章上获取第二张图片的PHP代码

| 我正在使用以下代码来从博客文章获取图片
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来删除第一张图像。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。