问题描述
|
我需要匹配模式
<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\",$tablecontent);
preg_match_all(\"|/<a.+class=\\\"item-link\\\".+href=\\\"(.*)\\\"[^>]*>\\.+<\\/a[^>]*>/|m\",$tablecontent);
print_r($tablecontent);
解决方法
尝试这个:
preg_match(\'/<a class=\"item-link\" href=\"([^\"]+)\">([^<]+)<\\/a>/\',$content,$matches);
, 这是执行此操作的正确方法:
$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 ...
}
对单个链接的矫kill过正,但这是处理完整HTML页面时最简单的方法。