【问题标题】:Need help with preg_replace of links with images (php) [duplicate]需要关于 preg_replace 图像链接的帮助(php)[重复]
【发布时间】:2011-11-12 05:32:33
【问题描述】:

可能重复:
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 灯箱。 请帮忙!

【问题讨论】:

    标签: php regex dom find hyperlink


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 我认为 OP 希望找到 img 标签内的所有 src 属性 a 具有 rel="lightbox" 的标签。您正在(尝试)查找具有rel="lightbox"a 标记的所有href 值。
      • 另请注意,您拼写为'herf' 而不是'href'
      • 哈哈,错别字了;操作员特别说href tag,然后find them all and put to an array,谢谢你
      猜你喜欢
      • 2011-05-09
      • 1970-01-01
      • 2011-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-18
      • 2014-03-11
      相关资源
      最近更新 更多