驗證 URL 格式是表單處理、API 輸入檢查的常見需求。PHP 內建 filter_var() 配合 FILTER_VALIDATE_URL 為最推薦做法;若需自訂規則(如限定網域、協定),則使用正則表達式。
<?php
function isValidUrl(string $url): bool
{
// FILTER_FLAG_HOST_REQUIRED 要求必須有主機名
// FILTER_FLAG_PATH_REQUIRED 要求必須有路徑(可選)
return (bool) filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED);
}
// 測試
$tests = [
'https://www.example.com' => true,
'https://example.com/path?query=1' => true,
'ftp://files.example.org' => true,
'www.example.com' => false, // 缺少 scheme
'https://' => false,
'not-a-url' => false,
];
foreach ($tests as $url => $expected) {
$result = isValidUrl($url);
echo "$url => " . ($result ? '✅' : '❌') . " (預期: " . ($expected ? '✅' : '❌') . ")" . PHP_EOL;
}
?>
以下正則支援 http/https/ftp、子網域、IP 位址、連接埠、路徑、查詢字串、片段:
<?php
function isValidUrlRegex(string $url): bool
{
// 修正原範例的正則錯誤:[] 內不需轉義 . -,支援 IP、localhost、國際化域名
$pattern = '
~^
(?: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*)? # 片段
$~ix
';
return (bool) preg_match($pattern, $url);
}
// 測試
$tests = [
'https://www.example.com',
'https://sub.domain.co.uk/path?a=1#section',
'ftp://192.168.1.1:21/files',
'https://localhost:8080',
'https://[2001:db8::1]/api',
'www.example.com', // 缺 scheme
'https://', // 不完整
];
foreach ($tests as $url) {
echo "$url => " . (isValidUrlRegex($url) ? '✅' : '❌') . PHP_EOL;
}
?>
| 特性 | filter_var() | 自訂正則 |
|---|---|---|
| 維護性 | 內建、標準化 | 需自行維護正則 |
| 彈性 | 固定規則(RFC 3986 子集) | 可限定網域、協定、長度等 |
| 效能 | 極快(C 實作) | 稍慢(PCRE 解析) |
| 國際化域名 (IDN) | 需先 idn_to_ascii() | 正則可直接支援 Unicode |
filter_var(),簡潔可靠。parse_url() 檢查 host。javascript:、data:、file: 等危險協定。<?php
$url = 'https://user:pass@www.example.com:443/path?query=1#fragment';
$parts = parse_url($url);
print_r($parts);
/*
Array
(
[scheme] => https
[host] => www.example.com
[port] => 443
[user] => user
[pass] => pass
[path] => /path
[query] => query=1
[fragment] => fragment
)
*/
?>
驗證 URL 格式首選 filter_var($url, FILTER_VALIDATE_URL);需自訂規則時撰寫嚴謹正則並搭配單元測試。記得驗證通過後再做正規化與安全過濾,確保資料品質與系統安全。