我想在html文件或文本中搜索链接中有"friend“的锚点。即:zack is your friend
然后,当它与一个锚匹配时,它应该返回href属性和锚(链接)。我尝试过用谷歌搜索,但到目前为止我还不能理解domXpath,其他示例只搜索href属性。我需要代码来证明这一点。
发布于 2013-12-01 03:27:22
Xpath可以做到这一点。xpath表达式可以包含节点的条件。因此,让我们开始选择文档中任意位置的所有元素:
//a
现在,在一个条件中使用node()获取所有子节点(元素和文本),将它们转换为一个string(),检查该字符串是否为子字符串“contains()”
//a[contains(string(node()), "friend")]
遍历节点并读取其中的数据。
$html = <<<'HTML'
<a href="foo.html">zack is your friend</a>
HTML;
$dom = new DOMDocument;
$dom->loadHtml($html);
$xpath = new DOMXpath($dom);
$nodes = $xpath->evaluate('//a[contains(string(node()), "friend")]');
foreach ($nodes as $node) {
var_dump(
array(
'href' => $node->getAttribute('href'),
'text' => $node->textContent
)
);
}https://stackoverflow.com/questions/20299440
复制相似问题