【问题标题】:extract url using PHP [duplicate]使用 PHP 提取 url [重复]
【发布时间】:2011-08-24 01:56:03
【问题描述】:

可能重复:
Grabbing the href attribute of an A element

嗨,我在 PHP 中有这个字符串

<iframe frameborder="0" width="320" height="179" src="http://www.dailymotion.com/embed/video/xinpy5?width=320&wmode=transparent"></iframe><br /><a href="http://www.dailymotion.com/video/xinpy5_le-buzz-pippa-middleton-agace-la-reine_news" target="_blank">Le buzz Pippa Middleton agace la Reine !</a> <i>par <a href="http://www.dailymotion.com/direct8" target="_blank">direct8</a></i>

我想使用 preg_match 或其他 php 函数从锚点 href 属性中提取 url

【问题讨论】:

    标签: php regex


    【解决方案1】:

    试试这个正则表达式

    (?<=href=\")[\w://\.\-]+
    

    【讨论】:

      【解决方案2】:

      你可以使用

      if (preg_match('#<a\s*[^>]*href="([^"]+)"#i', $string, $matches))
      echo $matches[0];
      

      【讨论】:

        【解决方案3】:

        Don't use regexes to parse HTML。使用 PHP DOM:

        $DOM = new DOMDocument;
        $DOM->loadHTML($str); // Your string
        
        //get all anchors
        $anchors = $DOM->getElementsByTagName('a');
        
        //display all hrefs
        for ($i = 0; $i < $anchors->length; $i++)
            echo $anchors->item($i)->getAttribute('href') . "<br />";
        

        如有必要,您可以先使用hasAttribute() 检查节点是否有href

        【讨论】:

          猜你喜欢
          • 2016-08-02
          • 1970-01-01
          • 2013-11-21
          • 2016-06-28
          • 1970-01-01
          • 2015-01-09
          • 1970-01-01
          • 2012-03-26
          • 1970-01-01
          相关资源
          最近更新 更多