What are some PHP functions that can help extract specific parts of a URL?

When working with URLs in PHP, you may need to extract specific parts such as the hostname, path, query parameters, or fragments. PHP provides several functions to help with this, such as parse_url(), parse_str(), and parse_url().

$url = "https://www.example.com/path/to/page?param1=value1&param2=value2#section";

// Extract hostname
$hostname = parse_url($url, PHP_URL_HOST);
echo "Hostname: " . $hostname . "\n";

// Extract path
$path = parse_url($url, PHP_URL_PATH);
echo "Path: " . $path . "\n";

// Extract query parameters
parse_str(parse_url($url, PHP_URL_QUERY), $query);
echo "Query parameters: ";
print_r($query);

// Extract fragment
$fragment = parse_url($url, PHP_URL_FRAGMENT);
echo "Fragment: " . $fragment . "\n";