I-M-JM
I-M-JM

Reputation: 15950

fetching img tag, and it's src value

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:

How can I do it?

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

Upvotes: 0

Views: 5568

Answers (4)

Karolis
Karolis

Reputation: 9562

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:

Upvotes: 5

morphles
morphles

Reputation: 2503

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/

Upvotes: 0

salathe
salathe

Reputation: 51950

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

Upvotes: 2

Darm
Darm

Reputation: 5659

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

Upvotes: 0

Related Questions