2011-12-25 65 views
-3

[抱歉,关于我的话题和标题,我没有足够的时间学习PHP DOM现在] 如何捕获a标签,包含一些文本和标签? 例如:正则表达式查找特定标签包含一些标签

<div> 
<a href="http://www.google.com/">Google COM</a> 
<a target="_blank" href="http://www.google.co.uk/">Google <span class="country">UK</span></a> 
</div> 
<span> 
<a id="italy" href="http://www.google.it/"><span class="country">Italy</span><strong> I</strong></a> 
<a class="link" href="#top">Top</a> 
</span> 

我想捕捉a,其中包含ItalyGoogle。 非常感谢。

+3

正则表达式是不利于这样的:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 - 它肯定比使用DOM更难。 – ThiefMaster 2011-12-25 20:38:39

回答

5

PHPDOM­Docs真的是这里最容易使用的工具,选择/表达式语法并不难:

$doc = new DOMDocument(); 
$doc->loadHTML($html); # your string 
$xpath = new DOMXpath($doc); 

$xpath->query("//a[text()[contains(., 'Italy') or contains(., 'Google')]]"); 

如果你只是想在某一父元素的样子,你可以轻松地添加它:

$xpath->query("//div/a[text()[contains(., 'Italy') or contains(., 'Google')]]"); 
+0

谢谢,但是当我运行你的脚本(http://pastebin.com/pwWAPgf5)时,它说:'警告:DOMXPath :: query()[domxpath.query]:'中的表达式无效。 – mrdaliri 2011-12-25 21:13:41

+0

表达式末尾还有一个']'。现在检查。 – 2011-12-25 21:42:06

相关问题