0

I have 2 image tags, one after another

<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">

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

I-M-JM
  • 15,732
  • 26
  • 77
  • 103
  • possible duplicate of [Grabbing the href attribute of an A element](http://stackoverflow.com/questions/3820666/grabbing-the-href-attribute-of-an-a-element) – Gordon Jul 25 '11 at 11:58

4 Answers4

5

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:

Karolis
  • 9,396
  • 29
  • 38
2

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');
}
salathe
  • 51,324
  • 12
  • 104
  • 132
0

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

Darm
  • 5,581
  • 2
  • 20
  • 18
0

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/

morphles
  • 2,424
  • 1
  • 24
  • 26