【问题标题】:Retrieve multiple value of a <a href> tag using php使用 php 检索 <a href> 标记的多个值
【发布时间】:2014-11-19 05:55:24
【问题描述】:

我需要使用php代码提取存储在&lt;a&gt;标签中的链接值。

我用下面的代码

$url = '<a title="Question" href="http://stackoverflow.com/questions/ask">t</a>';
preg_match("/href=\"(.*?)\"/i", $url, $matches);
print_r($matches);

通过上面的代码,我可以得到单个 href 的值。但它不适用于字符串中的多个href(即$url = '&lt;a title="Question" href="http://stackoverflow.com/questions/ask"&gt;t&lt;/a&gt;&lt;a href="x.php"&gt;x&lt;/a&gt;';)。我怎样才能做到这一点?

【问题讨论】:

    标签: php


    【解决方案1】:

    使用 DOM 解析器,这个例子应该可以帮助你:

    <?php
    $doc = new DOMDocument();
    $doc->loadHTML('<a title="Question" href="http://stackoverflow.com/questions/ask">t</a>');
    
    $elm = $doc->getElementsByTagName('a')->item(0);
    
    foreach ($elm->attributes as $attr) {
        echo $attr->name . ' ' . $attr->value . '<br>';
    }
    
    echo "Directly getting href: " . $elm->attributes->getNamedItem('href')->value;
    

    输出:

    title Question
    href http://stackoverflow.com/questions/ask
    Directly getting href: http://stackoverflow.com/questions/ask 
    

    演示:http://viper-7.com/EN1Usi

    文档:http://php.net/manual/en/class.domdocument.php

    【讨论】:

      【解决方案2】:

      使用preg_match_all() 获取所有匹配项,而不仅仅是第一个。

      $url = '<a title="Question" href="http://stackoverflow.com/questions/ask">t</a>&nbsp;<a href="x.php">x</a>';
      preg_match_all("/href=\"(.*?)\"/i", $url, $matches);
      print_r($matches);
      

      【讨论】:

      • 如果我们需要获取 href 和标识符类(即 ),还有一件事。我需要获取 fb url 类的 href意思是
      猜你喜欢
      • 2012-12-11
      • 2016-04-06
      • 1970-01-01
      • 2016-01-17
      • 2013-08-01
      • 2021-09-18
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多