开发者

fetching img tag, and it's src value

I have 2 image tags, one after another

<img class="c1 c2 c3" title="Image Title开发者_Go百科 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">

I want a regular expression that can fetch 2 things:

  • First 'img' tag
  • 'src' value from first 'img' tag

How can I do it?

P.S. do someone know where I can test regular expression online


Regular expression to match the first IMG tag and its src value:

$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);

Output:

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
)

There are many tools to test regular expressions online. Here are just a few of them:

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


Is there any special reason why you want to use a regular expression over more, generally, suitable tools like the DOM extension ?

A basic example of getting the first <img>'s src attribute might look like:

$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');
}


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


Try something like /(<img[^>]*)/ to get the first img tag(or any using backreference). And then use something like /src="([^"])/ to get src from tag string.

Answer to ps: http://www.spaweditor.com/scripts/regex/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜