To parse a URL in php, you can use the php parse_url() function and get an array with the URL scheme, host, path, query string, and other information.
$url = "https://daztech.com/php-parse-url?user=friend#hello";
print_r(parse_url($url));
//Output:
Array
(
[scheme] => https
[host] => daztech.com
[path] => /php-parse-url
[query] => user=friend
[fragment] => hello
)
If you want to only get a specific piece of information about a URL, you can pass a value to the optional ‘component’ parameter.
$url = "https://daztech.com/php-parse-url?user=friend#hello";
echo parse_url($url, PHP_URL_SCHEME) . "n";
echo parse_url($url, PHP_URL_HOST) . "n";
echo parse_url($url, PHP_URL_PATH) . "n";
echo parse_url($url, PHP_URL_QUERY) . "n";
echo parse_url($url, PHP_URL_FRAGMENT) . "n";
//Output:
https
daztech.com
/php-parse-url
user=friend
hello
When working with URLs in our programs, the ability to parse a URL and extract information about the URL is valuable.
In php, the parse_url() function allows us to easily extract information about a given URL.
We can use parse_url() to parse URLs and get information about the URL scheme, host, port, path, query and fragment.
Below is a simple example of how to use parse_url() to parse a URL in php.
$url = "https://daztech.com/php-parse-url?user=friend#hello";
print_r(parse_url($url));
//Output:
Array
(
[scheme] => https
[host] => daztech.com
[path] => /php-parse-url
[query] => user=friend
[fragment] => hello
)
Getting a Specific URL Component with parse_url() in php
With parse_url(), you can get a specific component of a URL by passing a value to the optional ‘component’ parameter of parse_url().
If the component you are looking for exists, parse_url() will return a string. If the component doesn’t exist, parse_url() will return NULL.
Below are a few examples of how to get specific components from a URL in php.
$url = "https://daztech.com/php-parse-url?user=friend#hello";
echo parse_url($url, PHP_URL_SCHEME) . "n";
echo parse_url($url, PHP_URL_HOST) . "n";
echo parse_url($url, PHP_URL_PATH) . "n";
echo parse_url($url, PHP_URL_QUERY) . "n";
echo parse_url($url, PHP_URL_FRAGMENT) . "n";
//Output:
https
daztech.com
/php-parse-url
user=friend
hello
Hopefully this article has been useful for you to learn how to parse a URL with the php parse_url() function.