Find image or iframe with regular expressions

我只是一个虾纸丫 提交于 2019-12-13 04:50:07

问题


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



来源:https://stackoverflow.com/questions/20682332/find-image-or-iframe-with-regular-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!