获取img标签,以及它的SRC值


fetching img tag, and it's src value

我有两个图像标签,一个接一个

<img class="c1 c2 c3" title="Image Title 1" src="http://example.com/image-1.jpg" alt="" width="620" height="521"><img class="c1 c2 c3" title="Image Title 2" src="http://example.com/image-2.jpg" alt="" width="620" height="521">

我想要一个正则表达式,可以获取两个东西:

  • 第一个'img'标签
  • 第一个'img'标签的'src'值

我该怎么做?

注:有人知道我可以在哪里测试正则表达式在线

匹配第一个IMG标签及其src值的正则表达式:

$subject = '<img class="c1 c2 c3" title="Image Title 1" src="http://example.com/image-1.jpg" alt="" width="620" height="521"><img class="c1 c2 c3" title="Image Title 2" src="http://example.com/image-2.jpg" alt="" width="620" height="521">';
preg_match('/<img's.*?'bsrc="(.*?)".*?>/si', $subject, $matches);
print_r($matches);
输出:

Array
(
    [0] => <img class="c1 c2 c3" title="Image Title 1" src="http://example.com/image-1.jpg" alt="" width="620" height="521">
    [1] => http://example.com/image-1.jpg
)

有很多工具可以在线测试正则表达式。这里只是其中的一些:

  • http://regex.larsolavtorvik.com/
  • http://www.spaweditor.com/scripts/regex/

您想要使用正则表达式而不是像DOM扩展这样更合适的工具,这有什么特殊的原因吗?

获取第一个<img>src属性的基本示例如下:

$subject = '<img class="c1 c2 c3" title="Image Title 1" src="http://example.com/image-1.jpg" alt="" width="620" height="521"><img class="c1 c2 c3" title="Image Title 2" src="http://example.com/image-2.jpg" alt="" width="620" height="521">';
$doc = new DOMDocument;
$doc->loadHTML($subject);
$imgs = $doc->getElementsByTagName('img');
// Echo first <img>'s src attribute if we found any <img>s
if ($imgs->length > 0) {
    echo $imgs->item(0)->getAttribute('src');
}

使用:preg_match('/<img [>]*src="([^"]*)"/i',$subject,$matches);

尝试像/(<img[^>]*)/这样的东西来获得第一个img标记(或任何使用反向引用)。然后使用/src="([^"])/之类的东西从标签字符串中获取src。

回答ps: http://www.spaweditor.com/scripts/regex/