简体   繁体   中英

Find image or iframe with regular expressions

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 :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM