正则表达式以捕获具有其所有HTML属性的图像

时间:2019-06-24 15:09:53

标签: php regex wordpress preg-match

我正在WordPress中使用以下代码(改编自this answer),以获取帖子中显示的第一张图片。

function twentytwelve_get_first_image() {
  global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  if ($output > 0){
        $first_img = $matches [1] [0];
    }
  return $first_img;
}

在第一个图像中包含一些CSS类或替代文本的情况下,例如:

<img src="http://localhost:8888/sitename/wp-content/uploads/2016/03/IMG_1470.jpg" alt="IMG_1470.JPG" class="alignnone size-full" scale="0">

此函数返回的图像没有其类和替代文本。在这种情况下:

<img src="http://localhost:8888/sitename/wp-content/uploads/2016/03/IMG_1470.jpg" scale="0">

如何修改它以返回具有所有HTML属性的图像?

我尝试修改了$output被定义为的行

$output = preg_match_all('/<img.*>/i', $post->post_content, $matches);

但是导致了以下通知: Notice: Undefined offset: 1 in [php file] 并且没有返回图像。

更新: 按照建议,这是regex with example text to match in a parser

0 个答案:

没有答案