使用 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>。DOMDocument:$dom = new DOMDocument();
@$dom->loadHTML($html);
$links = [];
foreach ($dom->getElementsByTagName('a') as $a) {
$links[] = ['url' => $a->getAttribute('href'), 'name' => trim($a->textContent)];
}