Need help with preg_replace of links with images (php) [duplicate]
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.)
精彩评论