從 HTML 字串中提取形如 news.qq.com 的二級域名鏈接,並同時獲取鏈接文字(如「新聞」),需處理域名後帶路徑的情況(如 ent.qq.com/movie)。
<a href="..."> 標籤結構。var html = '<a href="https://mil.qq.com/" target="_blank">軍事</a>...<a href="https://ent.qq.com/movie" target="_blank">電影</a>';
var regex = /<a\s+href="([^"]+)"[^>]*>([^<]+)<\/a>/gi;
var matches = [];
var match;
while ((match = regex.exec(html)) !== null) {
matches.push({
url: match[1],
text: match[2]
});
}
console.log(matches);
// 輸出: [{url: "https://mil.qq.com/", text: "軍事"}, {url: "https://ent.qq.com/movie", text: "電影"}, ...]
$html = '...'; // 同樣的 HTML 字串
$pattern = '/<a\s+href="([^"]+)"[^>]*>([^<]+)<\/a>/i';
preg_match_all($pattern, $html, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
echo "URL: {$m[1]}, Text: {$m[2]}\n";
}
// 從 URL 中提取 hostname (JavaScript)
var url = new URL(match[1]); // 需完整 URL 含協議
var hostname = url.hostname; // 如 "news.qq.com"
var parts = hostname.split('.');
if (parts.length >= 3) {
var secondLevel = parts[parts.length - 2] + '.' + parts[parts.length - 1]; // "qq.com"
var subDomain = parts[0]; // "news"
}