函式名稱:parse_url()
適用版本:所有版本的PHP(5.x到最新版本)
函式描述:parse_url()函式用於解析URL字串,並返回一個關聯陣列,包含URL的各個組成部分。URL的組成部分包括協議、主機名、埠號、路徑、查詢字串和片段。
語法:mixed parse_url ( string $url [, int $component = -1 ] )
引數:
- $url:需要解析的URL字串。
- $component(可選):指定要返回的URL元件。預設值為-1,表示返回所有元件。可選值有:
- PHP_URL_SCHEME:協議(例如http、https)。
- PHP_URL_HOST:主機名。
- PHP_URL_PORT:埠號。
- PHP_URL_USER:使用者名稱。
- PHP_URL_PASS:密碼。
- PHP_URL_PATH:路徑。
- PHP_URL_QUERY:查詢字串。
- PHP_URL_FRAGMENT:片段。
返回值:如果指定了$component引數,則返回對應的URL元件。如果未指定$component引數,則返回一個包含所有URL元件的關聯陣列。如果解析失敗,則返回false。
示例:
- 解析完整URL並返回所有元件:
$url = "https://www.example.com:8080/path/to/file.php?param1=value1¶m2=value2#fragment";
$result = parse_url($url);
print_r($result);
輸出結果:
Array
(
[scheme] => https
[host] => www.example.com
[port] => 8080
[path] => /path/to/file.php
[query] => param1=value1¶m2=value2
[fragment] => fragment
)
- 解析URL並返回指定的元件(主機名和路徑):
$url = "https://www.example.com/path/to/file.php?param1=value1¶m2=value2#fragment";
$host = parse_url($url, PHP_URL_HOST);
$path = parse_url($url, PHP_URL_PATH);
echo "Host: $host\n";
echo "Path: $path\n";
輸出結果:
Host: www.example.com
Path: /path/to/file.php
- 解析URL並返回指定的元件(查詢字串):
$url = "https://www.example.com/path/to/file.php?param1=value1¶m2=value2#fragment";
$query = parse_url($url, PHP_URL_QUERY);
echo "Query: $query\n";
輸出結果:
Query: param1=value1¶m2=value2
注意:parse_url()函式只能解析標準的URL字串,如果URL字串不符合標準格式,解析可能會失敗。
熱門工具排行榜