What are common pitfalls or challenges when trying to extract specific parts of a URL in PHP?

One common pitfall when trying to extract specific parts of a URL in PHP is not properly handling different URL formats or variations. To solve this issue, you can use PHP's built-in parse_url function to break down a URL into its components and then access the specific parts you need.

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

// Parse the URL
$parsed_url = parse_url($url);

// Get the host
$host = $parsed_url['host'];
echo "Host: " . $host . "\n";

// Get the path
$path = $parsed_url['path'];
echo "Path: " . $path . "\n";

// Get the query string
parse_str($parsed_url['query'], $query_params);
echo "Query Params: ";
print_r($query_params);