2011-06-13 74 views
1

我需要匹配的模式我怎样才能匹配的模式如下

<a class="item-link" href="NEED TO GET THIS PART">AND THIS PART</a> 

我尝试了所有三个正则表达式模式,但没有人可以帮助我。

preg_match_all("/<a.*(?:[^class=\"item-link\"=]*)class=\"item-link\"(?:[^href=]*)href=(?:'|\")?(.*)(?:'|\")(?:[^>]*)>(.*)<\/a>/", $content, $tablecontent); 
preg_match_all("|/<a (?:[^href=]*)href=(?:'|\")?(.*)(?:'|\")(?:[^>]*)>(.*)<\/a>/|s", $content, $tablecontent); 
preg_match_all("|/<a.+class=\"item-link\".+href=\"(.*)\"[^>]*>\.+<\/a[^>]*>/|m", $content, $tablecontent); 
print_r($tablecontent); 
+3

不要使用正则表达式,请使用HTML解析器。 – 2011-06-13 17:09:04

+1

问题的背景是什么?如果你想解析HTML,那么使用HTML解析器。 – Matthew 2011-06-13 17:09:19

+0

HTML语法分析器...我不熟悉它..我试图写上面的代码,但可以找到它的工作 – 2011-06-13 17:14:47

回答

1

试试这个:

preg_match('/<a class="item-link" href="([^"]+)">([^<]+)<\/a>/', $content, $matches); 
+0

preg_match(): – 2011-06-13 17:12:50

+0

我修正了......未知修饰符'a'对不起。我忘了在的前面添加\。 – 2011-06-13 17:15:50

+0

以及代码显示没有输出..数组( – 2011-06-13 17:18:03

1

这是做到这一点的正确方法:

$html = '<a class="item-link" href="NEED TO GET THIS PART">AND THIS PART</a>'; 

$dom = new DOMDocument(); 
$dom->loadHTML($html); 

$xp = new XPath($dom); 

$results = $xp->query('//a[class="item-link"]'); 

foreach ($results as $link) { 
    $href = $link->getAttribute('href'); 
    $text = $link->nodeValue; 

    ... do your stuff here ... 
} 

矫枉过正一个链接,但截至目前为止最简单的方法,当一个完整的处理HTML页面。