Alvins
Alvins

Reputation: 887

PHP preg_match image between html tags

I've got an html template like this:

    <div class="cont">
    <div class="...">
    <p>...<p>
    <img alt="" class="popup" src="DESIRED IMAGE LINK" style="..." /></p><p>...</p>
    ....

And i want to extract "DESIRED IMAGE LINK" inside the "" tag, currently i'm using this:

$pattern = '<div class="cont">.*?src=["\']?([^"\']?.*?(png|jpg|jpeg|gif))["\']?/i';
if (preg_match($pattern, $content, $image))
     .....

But it doesn't work, the error is:

    warning: preg_match() [function.preg-match]: Unknown modifier '.' 

How can i fix it? Thanks

Upvotes: 1

Views: 634

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173662

The answer is, don't use regular expressions.

$contents = <<<EOS
<div class="cont">
    <div class="...">
    <p>...<p>
    <img alt="" class="popup" src="DESIRED IMAGE LINK" style="..." /></p><p>...</p>
EOS;

$doc = new DOMDocument;
libxml_use_internal_errors(true);
$doc->loadHTML($contents);
libxml_clear_errors();

$xp = new DOMXPath($doc);

// get first image inside div.cont
foreach($xp->query('//div[@class="cont"]//img[1]') as $node) {
        // output the src attribute
        echo $node->getAttribute('src'), PHP_EOL;
}

See also: DOMDocument DOMXPath

Upvotes: 3

piddl0r
piddl0r

Reputation: 2449

If you're planning on parsing html try using DOM with xpath.

Upvotes: 1

Halcyon
Halcyon

Reputation: 57721

$pattern = '/<div class="cont">.*?src=["\']?([^"\']?.*?(png|jpg|jpeg|gif))["\']?/i

You're missing your leading delimiter character /.

Upvotes: 0

Related Questions