【问题标题】:Matching HTML link with a specific title [closed]将 HTML 链接与特定标题匹配 [关闭]
【发布时间】:2012-02-06 00:40:18
【问题描述】:

如何从具有特定开头标题的 HTML 链接中检索 URL?

例如:

<a href="http://urltoretrieve.ext/" title="specific title rest of all title">something</a>
<a href="http://otherurl.ext/" title="a generic title">somethingelse</a>

并使用 PHP 检索:

http://urltoretrieve.ext/

谢谢!

【问题讨论】:

  • my $url='http://urltoretrieve.ext/
  • 如果标签不同,比如querypath,那么htmlqp($html)-&gt;find('a[title^="specific"]')-&gt;attr("href") 会很容易。
  • @mario 将其作为答案。我将正则表达式标签交换为 html 解析,因为 OP 根本没有在问题中提到正则表达式,所以我假设 OP 只是假设正则表达式是正确的方法。

标签: php html-parsing


【解决方案1】:

您可以使用https://gist.github.com/1358174 和这个XPath

//a[starts-with(@title, "specific title")]/@href

这个查询的意思是:

//a                      find all a elements in the html
[                        that
starts-with(             
    @title               has a title attribute
    'specific-title'     starting with this value
)                        
]                        
/@href                   and return their href attribute

示例 (demo):

$result = xpath_match_all(
    '//a[starts-with(@title, "specific title")]/@href', 
    $yourHtmlAsString
);

输出:

array(2) {
  [0]=>
  array(1) {
    [0]=>
    string(38) "<href>http://urltoretrieve.ext/</href>"
  }
  [1]=>
  array(1) {
    [0]=>
    string(25) "http://urltoretrieve.ext/"
  }
}

结果是一个数组,其中包含找到的属性节点的序列化 innerHTML 和 outerHTML。如果您不了解节点是什么,请查看DOMDocument in php

另见How do you parse and process HTML/XML in PHP?

【讨论】:

  • 哈,没必要。这已经很好地回答了它。超酷的迷你功能!
  • 为什么结果检索到我 2 个数组?
  • @davelab 将找到的属性节点的 innerHTML 和 outerHTML 序列化,因为该函数无法知道您想要哪个。如果那不是你想要的,你必须学习如何使用 DOM。 gist 中的源代码是一个很好的起点,StackOverflow 上也有很多示例。
  • 好的,对于 xPath 解决方案:如何排除 outerHTML 数组?
  • @davelab 它是一个数组,所以如果您只对 innerHTML 字符串/属性值感兴趣,只需访问 innerHTML 的索引,例如$结果[1][0]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-13
  • 1970-01-01
  • 2015-05-04
  • 1970-01-01
  • 2010-12-12
相关资源
最近更新 更多