PHP 提供 parse_url() 分解 URL 結構,parse_str() 將查詢字串解析為變數陣列,兩者結合即可輕鬆提取參數。
mixed parse_url ( string $url [, int $component = -1 ] )
scheme、host、port、user、pass、path、query、fragment。$component 可直接取得對應字串(PHP_URL_PORT 返回整數)。void parse_str ( string $str [, array &$arr ] )
$arr 則存入陣列,否則直接註冊到當前符號表(不推薦)。magic_quotes_gpc 影響,開啟時會自動 addslashes()。<?php
$url = 'https://www.example.com/ad.php?id=325&action=index&page=3';
$urlarr = parse_url($url);
parse_str($urlarr['query'], $parr);
print_r($urlarr);
/* 輸出:
Array(
[scheme] => http
[host] => www.example.com
[path] => /ad.php
[query] => id=325&action=index&page=3
)
*/
print_r($parr);
/* 輸出:
Array(
[id] => 325
[action] => index
[page] => 3
)
*/
?>
htmlspecialchars() 或型別轉換。ids[]=1&ids[]=2,parse_str 會自動生成陣列 $parr['ids'] = [1,2]。urldecode() 使用。掌握這兩個函數,處理 URL 參數將不再需要正則表達式,代碼更簡潔健壯。