parse_url
Splits a URL into its parts.
Syntax
parse_url(string $url, int $component = -1): int|string|array|null|falseParameters
| Parameter | Type | Description |
|---|---|---|
| $url | string | The URL. |
| $component | int | Optional. Which part to return: `PHP_URL_HOST`, `PHP_URL_PATH`, `PHP_URL_QUERY`. |
Return value
int|string|array|null|falseAn array of the parts, or a single part.
Examples
Separate parts of a URL:
<?php
$url = 'https://example.com/products/tea?page=2';
echo parse_url($url, PHP_URL_HOST), "\n";
echo parse_url($url, PHP_URL_PATH), "\n";
echo parse_url($url, PHP_URL_QUERY);Output:
example.com
/products/tea
page=2The parameters into an array:
<?php
parse_str(parse_url('https://example.com/?q=tea&page=2', PHP_URL_QUERY), $params);
echo json_encode($params);Output:
{"q":"tea","page":"2"}Notes
The function does not check whether the URL is valid. Use filter_var($url, FILTER_VALIDATE_URL) for that.
See also
- http_build_query — Builds a URL query string from an array.
- urlencode — Encodes a string for use in a URL.
- basename — Returns the last part of a path — the file name.
Related recipes
In the tutorial
- HTTP requests and responses — How PHP receives a request and builds a response — the request method and address, headers, status codes, redirects and JSON responses.