开发者

Need help with preg_replace of links with images (php) [duplicate]

This question already exists: Closed 11 years ago. 开发者_高级运维

Possible Duplicate:

How to parse HTML with PHP?

Grabbing the href attribute of an A element

I have some random text with images in a href tag like this:

<a title="Some title" rel="lightbox" href="http://www.test.com/DSCF0733.jpg"><img class="alignleft size-thumbnail wp-image-504" title="some title" src="http://www.test.com/Dhghjkhjl33-150x150.jpg" alt="description" width="145" height="145" /></a>

I want to find them all and put to an array. Text can contain other links, but we need only with rel lightbox. Please, help!


You could use the built in DOMDocument(), simple yet effective & safer then regex...

<?php 
$site=file_get_contents('http://example.com');

$xml = new DOMDocument();
@$xml->loadHTML($site);


foreach($xml->getElementsByTagName('a') as $links) {
    //Check for lightbox within the link
    if($links->getAttribute('rel')=='lightbox'){ 
        //Assign
        $imgLinks[]=$links->getAttribute('href');
    }
}

print_r($imgLinks);
?>


For simplicity use phpQuery or QueryPath:

include "qp.phar";
foreach (htmlqp($html)->find("a[rel=lightbox]") as $a) {
    $links[] = $a->attr("href");
}

But you can also modify the contained text or other attributes. (The preg_replace part of your question might need elaboration.)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜