需要帮助preg_replace链接图像(php)

时间:2011-09-07 14:28:25

标签: php regex dom find hyperlink

  

可能重复:
  How to parse HTML with PHP?
  Grabbing the href attribute of an A element

我在href标签中有一些带有图像的随机文本,如下所示:

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

我想找到它们并放入一个数组。文本可以包含其他链接,但我们只需要使用rel lightbox。 请帮助!

2 个答案:

答案 0 :(得分:2)

您可以使用内置的DOMDocument(),简单而有效的&amp;比正则表达更安全...

<?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);
?>

答案 1 :(得分:1)

为简单起见,请使用phpQuery or QueryPath

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

但您也可以修改包含的文本或其他属性。 (你的问题的preg_ replace 部分可能需要详细说明。)