[PHP] URL を構成要素に分解する

作成日: 2026年08月01日

PHP の parse_url 関数を使用すると、URL をスキーム、ホスト、パス、クエリ文字列などの構成要素に分解することができます。

<?php

$url = 'https://example.com:8080/path/to/page?name=Tom&age=20#profile';

$parts = parse_url($url);
var_dump($parts);

実行結果は下記のとおりです。

array(6) {
  ["scheme"]=>
  string(5) "https"
  ["host"]=>
  string(11) "example.com"
  ["port"]=>
  int(8080)
  ["path"]=>
  string(13) "/path/to/page"
  ["query"]=>
  string(15) "name=Tom&age=20"
  ["fragment"]=>
  string(7) "profile"
}

特定の構成要素だけを取得したい場合は、第 2 引数に PHP_URL_HOSTPHP_URL_PATH などの定数を指定します。

PHP