PHP函数来抓取第一个图像


PHP function to scrape first image

在Wordpress博客中,我使用以下函数来抓取页面(单帖子视图)并找到第一个图像,如果没有找到,则使用默认图像:

    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 = "http://custome_url_for_default_image.png";
  }
  return $first_img;
}

我试图在汤博乐主题中按原样粘贴它,但遇到了一些问题(它不是作为PHP函数加载的)。我肯定错过了什么。如果有人有解决这个问题的想法,我很乐意尝试。

谢谢,

第页。

最好的方法是避免使用正则表达式解析HTML。

尝试使用DOMDocument:

function catch_that_image() {
    global $post;
    $dom = new DOMDocument();
    $dom->loadHtml($post->post_content);
    $imgTags = $dom->getElementsByTagName('img');
    if ($imgTags->length > 0) {
        $imgElement = $imgTags->item(0);
        return $imgElement->getAttribute('src');
    } else {
        return 'http://custome_url_for_default_image.png';
    }
}