萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP URL 格式驗證:正則表達式與 filter_var 兩種做法

前言

驗證 URL 格式是表單處理、API 輸入檢查的常見需求。PHP 內建 filter_var() 配合 FILTER_VALIDATE_URL 為最推薦做法;若需自訂規則(如限定網域、協定),則使用正則表達式。

方法一:filter_var() 內建驗證(推薦)

<?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

實務建議

  1. 一般表單驗證:優先用 filter_var(),簡潔可靠。
  2. 需限定特定網域(如只允許自家域名):改用正則或結合 parse_url() 檢查 host。
  3. 儲存前務必 正規化:統一小寫 scheme/host、移除預設連接埠、編碼路徑。
  4. 資安考量:拒絕 javascript:、data:、file: 等危險協定。

補充:parse_url() 解析 URL 結構

<?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);需自訂規則時撰寫嚴謹正則並搭配單元測試。記得驗證通過後再做正規化與安全過濾,確保資料品質與系統安全。

copyright © 萬盛學電腦網 all rights reserved