從使用者輸入、文章內容、郵件中提取 URL 是常見需求。單純用正則表達式容易漏配或誤判;現代做法結合 DOMDocument 解析 HTML 鏈結,純文字則用嚴謹正則。本文提供兩種方案完整實作。
採用 RFC 3986 簡化版正則,平衡精確度與效能:
<?php
/**
* 從純文字提取所有 URL
* @param string $text 來源文字
* @return string[] 唯一 URL 陣列
*/
function extractUrlsFromText(string $text): array
{
// 正則說明:
// (?:https?|ftp):// 協定
// (?: 主機部分
// (?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,} | 域名
// \d{1,3}(?:\.\d{1,3}){3} | IPv4
// \[[a-fA-F0-9:]+\] IPv6
// localhost 本機
// )
// (?::\d{1,5})? 選擇性連接埠
// (?:/[^\s?#]*)? 路徑
// (?:\?[^\s#]*)? 查詢字串
// (?:#\S*)? 片段
$pattern = '
~(?
(?:https?|ftp)://
(?:
(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}
|
\d{1,3}(?:\.\d{1,3}){3}
|
\[[a-fA-F0-9:]+\]
|
localhost
)
(?::\d{1,5})?
(?:/[^\s?#]*)?
(?:\?[^\s#]*)?
(?:#\S*)?
)~ix
';
preg_match_all($pattern, $text, $matches);
// 去重並過濾空值
return array_values(array_unique(array_filter($matches['url'] ?? [])));
}
// 測試
$text = << https://www.example.com
[1] => https://sub.domain.co.uk/path?query=1#anchor
[2] => ftp://files.example.org
[3] => https://192.168.1.1:8080
[4] => https://[2001:db8::1]/api
)
*/
?>
適用於已是 HTML 內容,需提取 <a href="...">、<img src="...">、<link href="..."> 等標籤屬性。
<?php
/**
* 從 HTML 內容提取指定標籤的屬性 URL
* @param string $html HTML 內容
* @param string $tag 標籤名稱 (a, img, link, script, iframe...)
* @param string $attr 屬性名稱 (href, src)
* @return string[] 唯一 URL 陣列
*/
function extractUrlsFromHtml(string $html, string $tag = 'a', string $attr = 'href'): array
{
libxml_use_internal_errors(true); // 抑制 HTML 解析錯誤警告
$dom = new DOMDocument();
$dom->loadHTML('' . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
$xpath = new DOMXPath($dom);
$nodes = $xpath->query("//$tag[@$attr]");
$urls = [];
foreach ($nodes as $node) {
$url = $node->getAttribute($attr);
if ($url !== '') {
$urls[] = $url;
}
}
return array_values(array_unique($urls));
}
// 測試
$html = <<
連結 1
相對路徑
<?php
function toAbsoluteUrl(string $baseUrl, string $relativeUrl): string
{
// 已是絕對 URL 或協定相對 (//example.com)
if (preg_match('~^https?://~i', $relativeUrl) || str_starts_with($relativeUrl, '//')) {
return str_starts_with($relativeUrl, '//') ? 'https:' . $relativeUrl : $relativeUrl;
}
$base = parse_url($baseUrl);
$basePath = rtrim($base['path'] ?? '/', '/');
// 解析相對路徑 (處理 ../, ./)
$parts = explode('/', $basePath);
$relParts = explode('/', $relativeUrl);
foreach ($relParts as $part) {
if ($part === '' || $part === '.') continue;
if ($part === '..') array_pop($parts);
else $parts[] = $part;
}
$newPath = '/' . implode('/', $parts);
return $base['scheme'] . '://' . $base['host'] . ($base['port'] ?? '') . $newPath;
}
// 測試
echo toAbsoluteUrl('https://example.com/dir/page.html', '../other.jpg');
// https://example.com/other.jpg
?>
<?php
function isUrlReachable(string $url, int $timeout = 5): bool
{
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_NOBODY => true, // HEAD 請求
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP Bot)',
CURLOPT_SSL_VERIFYPEER => false, // 測試用,生產請驗證
]);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
return $code >= 200 && $code < 400;
}
// 注意:大量檢查會很慢,建議非同步佇列處理
?>
| 場景 | 推薦方案 | 理由 |
|---|---|---|
| 純文字內容 (留言、郵件、日誌) | 正則 extractUrlsFromText() | 快速、無需解析 HTML、支援非標準標記 |
| HTML 內容 (網頁抓取、編輯器輸出) | DOMDocument + XPath | 正確處理屬性跳脫、相對路徑、巢狀標籤、編碼 |
| 需提取多種標籤 (a, img, link, script) | DOMDocument 多次查詢或單次 XPath //@href | //@src | 結構化、可擴展 |
| 效能極致要求 (百萬字串) | 預編譯正則 + JIT (PHP 8.0+) | 避免 DOM 解析開銷 |
提取 URL 選擇:純文字用嚴謹正則、HTML 用 DOMDocument。正則務必測試邊界案例 (IPv6、國際化域名、片段、查詢字串);DOM 解析記得 libxml_use_internal_errors(true) 抑制警告。提取後建議去重、正規化、選擇性驗證可達性。