Find image or iframe with regular expressions

2019-09-19 01:40发布

问题:

I've got the following code, it spits out the first image of each post, on 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

  }
  echo "<img src=" . $first_img . ">";
}

However, I also need to catch the first iframe, and echo whichever is first. I'm not experienced with regular expressions, so any help or resources would be great :)

回答1:

Use the |(or) operator. Replace the img with (img|iframe).