如何使用php从html页面提取特定的链接



我正在尝试Href链接从标签使用正则表达式,但我无法检索链接,有人可以帮助我实现这一点,这里是我试图从HTML页面提取的链接。/u/0/uc?export=download&confirm=EY_S&id=fileid这是我的php函数

<?php
function dwnload($url)
{
$scriptx = "";
$internalErrors = libxml_use_internal_errors(true);
$dom = new DOMDocument();
@$dom->loadHTML(curl($url));
foreach ($dom->getElementsByTagName('a') as $k => $js) {
$scriptx .= $js->nodeValue;
}
preg_match_all('#bhttps?://[^,s()<>]+(?:([wd]+)|([^,[:punct:]s]|/))#', $scriptx, $match);
$vlink = "";
foreach ($match[0] as $c) {
if (strpos($c, 'export=download') !== false) {
$vlink = $c;
}
}
return $vlink; 
}?>

感谢

您正在连接链接文本。这没有道理。如果您尝试提取链接,DOMNode::getElementsByTagName()已经完成了这项工作。你只需要过滤一下结果。

让我们考虑一个小的HTML片段:
$html = <<<'HTML'
<a href="/u/0/uc?export=download&amp;confirm=EY_S&amp;id=fileid">SUCCESS</a>
<a href="/another/link">FAILURE</a>
HTML;

现在迭代a元素并通过它们的href属性过滤它们。

$document = new DOMDocument();
$document->loadHTML($html);
foreach ($document->getElementsByTagName('a') as $a) {
$href = $a->getAttribute('href');
if (strpos($href, 'export=download') !== false) {
var_dump([$href, $a->textContent]);
}
}

输出:

array(2) {
[0]=>
string(46) "/u/0/uc?export=download&confirm=EY_S&id=fileid"
[1]=>
string(7) "SUCCESS"
}

现在,如果这是一个字符串匹配,则可以使用Xpath表达式:

$document = new DOMDocument();
$document->loadHTML($html);
$xpath = new DOMXpath($document);
foreach ($xpath->evaluate('//a[contains(@href, "export=download")]') as $a) {
var_dump([$a->getAttribute('href'), $a->textContent]);
}

或者将Xpath表达式与更具体的正则表达式组合:

$pattern = '((?:\?|&)export=download(?:&|$))';
foreach ($xpath->evaluate('//a[contains(@href, "export=download")]') as $a) {
$href = $a->getAttribute('href');
if (preg_match($pattern, $href)) {
var_dump([$href, $a->textContent]);
}
}

最新更新