萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 正則提取網頁所有超連結(URL 與錨文字)

使用 preg_match_all 匹配 <a href=...>...</a> 模式,同時捕獲 URL 與連結文字,返回關聯陣列。

函數實作

function get_all_url(string $html): array {
    preg_match_all('/<a\s+href=["\']?([^"\'>\s]+)["\']?[^>]*>([^<]+)<\/a>/i', $html, $matches);
    return [
        'name' => $matches[2],  // 錨文字
        'url'  => $matches[1]   // 連結地址
    ];
}

正則解析

  • <a\s+href=:匹配 <a href=(允許屬性順序變化需更複雜正則)。
  • ["\']?([^"\'>\s]+)["\']?:捕獲 URL(單/雙引號或無引號)。
  • [^>]*>([^<]+)<\/a>:跳過其他屬性,捕獲連結文字直到 </a>。

進階建議

  • 真實頁面常含 JavaScript 生成連結、相對路徑、空白屬性等,正則極易遺漏/誤匹配。
  • 強烈建議使用 DOMDocument:
$dom = new DOMDocument();
@$dom->loadHTML($html);
$links = [];
foreach ($dom->getElementsByTagName('a') as $a) {
    $links[] = ['url' => $a->getAttribute('href'), 'name' => trim($a->textContent)];
}
copyright © 萬盛學電腦網 all rights reserved