HTML 結構不規則,需提取所有 <a> 標簽的 href 與鏈接文本。
$str = '<a id="top8" href="https://list.MP3.baidu.com/song/A.htm?top8" class="p14" target="_top">歌曲列表</a><br>
<a target="_blank" id="bp" href="https://list.mp3.baidu.com/list/bangping.html" class="p14">中文金曲榜</a><br>
<td nowrap="nowrap">• <a id="top19" href="qingyinyue.html?top19" class="p14" target="_top">輕音樂</a></td>';
$pat = '/<a(.*?)href="(.*?)"(.*?)>(.*?)<\/a>/i';
preg_match_all($pat, $str, $m);
<a(.*?):非貪婪匹配標簽屬性href="(.*?)":捕獲組 2 — 鏈接地址(.*?):非貪婪跳過其餘屬性>(.*?)<\/a>:捕獲組 4 — 鏈接文本/i:大小寫不敏感print_r($m[2]); // 所有 href
print_r($m[4]); // 所有鏈接文本
// 或構建列表
for ($i = 0; $i < count($m[2]); $i++) {
echo '<li><a href="' . $_SERVER['PHP_SELF'] . '?url=' . urlencode($m[2][$i]) . '">' . $m[4][$i] . '</a>';
}
Array(
[0] => https://list.mp3.baidu.com/song/A.htm?top8
[1] => https://list.mp3.baidu.com/list/bangping.html
[2] => qingyinyue.html?top19
)
Array(
[0] => 歌曲列表
[1] => 中文金曲榜
[2] => 輕音樂
)
提示:複雜 HTML 解析建議使用
DOMDocument+DOMXPath,正則僅適用於結構相對固定、輕量級提取場景。