使用PHP preg_match_all获取图像?w=最后


PHP preg_match_all to get images with ?w= in last

我试图使用preg_match_all获取图像,但无法正确获取,这是我的代码。我的问题是,我有一些图片带有.img文本,还有一些带有.jpg?w=655&;h=357,我不需要.img,但需要它可以拥有的所有其他有效图像?w=655&;h=357在最后或刚刚.jpg或.png 中

$post ='
<img width="1" height="1" src="http://pi.feedsportal.com/r/180265248066/u/49/f/648326/c/35070/s/34410e29/a2t.img" border="0"/></br>
    <img width="1" height="1" src="http://9to5mac.files.wordpress.com/2013/11/screen-shot-2013-11-29-at-5-17-15-pm.png?w=655&#038;h=357" border="0"/></br>
    <img src="http://images.macrumors.com/article-new/2013/11/mlb.png" alt="MLB" title="mlb.png" width="175" height="175" class="alignright"/></br>
 ';
function catch_that_image($post) {
  global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all("<img.+?src=['"']([^'"]*'.(gif|jpg|jpeg|png).*)['"'].+?>", $post, $matches);
  $first_img = $matches [1] [0];
  return $first_img;
}
echo catch_that_image($post);

输出为

http://images.macrumors.com/article-new/2013/11/mlb.png" alt="MLB" title="mlb.png" width="175" height="175" class="alignright

我只需要url直到.png

感谢

不要使用正则表达式解析HTML。请改用DOM解析器:

$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('img') as $image) {
    $src =  $image->getAttribute('src');
    $extension = pathinfo($src, PATHINFO_EXTENSION);
    if ($extension !== 'img') {
        echo $src . PHP_EOL;
    }
}

在线演示