我正在使用以下代码从博客文章中抓取图片:
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;
}
现在,我需要一些帮助来介绍一个小修改。这就是我要找的东西:我希望代码忽略第一个图像,抓住它找到的第二个图像,如果没有找到第二个图像,则使用默认图像(后备图片)。
答案 0 :(得分:1)
我是QueryPath项目的忠实粉丝,它允许您像jQuery一样使用HTML文档。把咕噜咕噜的工作从这些任务中解脱出来。试一试,让我知道这是否有助于你!
答案 1 :(得分:0)
我在第二个答案@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来删除第一张图片。