dppxp79175 2013-09-26 22:01
浏览 29

使用preg_match_all和curl [duplicate]获取<a>标签的HREF

This question already has an answer here:

It's been a couple of days now that I am trying to find a way to solve my problem. I use CURL to get the content of a webpage and then use prey_match_all to use the content on my style, but I've got a problem when it's time to find some < a > tags in the document.

I want preg_match_all to find all < a > tags that are followed by a < strong > tag and than store all href values of these < a > tags in a array variable.

Here's what I've thought :

preg_match_all("~(<a href=\"(.*)\"><strong>\w+<\/strong>)~iU", $result, $link);

It's returning me :

Array ( [0] => Array ( ) [1] => Array ( ) [2] => Array ( ) )

Can somebody help me please !!

</div>
  • 写回答

2条回答 默认 最新

  • donglun1918 2013-09-26 22:10
    关注

    I strongly recommend you go with DomDocument

    This code should do the trick...

    <?php
    
    /**
    * @author Jay Gilford
    * @edited KHMKShore:stackoverflow
    */
    
    /**
    * get_links()
    * 
    * @param string $url
    * @return array
    */
    function get_links($url) {
    
      // Create a new DOM Document to hold our webpage structure
      $xml = new DOMDocument();
    
      // Load the url's contents into the DOM (the @ supresses any errors from invalid XML)
      @$xml->loadHTMLFile($url);
    
      // Empty array to hold all links to return
      $links = array();
    
      //Loop through each <a> and </a> tag in the dom
      foreach($xml->getElementsByTagName('a') as $link) {
        //if it has a strong tag in it, save the href link.
        if (count($link->getElementsByTagName('strong')) > 0) {
            $links[] = array('url' => $link->getAttribute('href'), 'text' => $link->nodeValue);
        }
      }
    
      //Return the links
      return $links;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥150 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装