PHP function to extract components from an URL

PHP function to extract components from an URL

You want to extract the protocol, domain name, path, or other significant component of a URL. Use the parse_url() function to automatically split the URL into its constituent parts. The parse_url() function is one of most useful URL manipulation function in PHP.

Ita takes a parameter of a Uniform Resource Locator (URL), and splitting it into its individual components. The resulting associative array contains separate keys for the protocol, host name, port number, remote path, and  GET  arguments. You can then easily access and use these keys for further processing.

// Define URL 
$url = "http://www.yourdomain.com:80/mobile-css/jquery/blog/article.php?id=179&page=5";

// Parse URL into associative array
$data = parse_url($url);

// print URL components
foreach ($data as $k=>$v) {
    echo "$k: $v \n";
}

Consider the output of the previous script, which illustrates this:

scheme: http

host: www.yourdomain.com

port: 80

path: /mobile-css/jquery/blog/article.php

query: id=179&page=5

Enjoy! Was this information useful? What other tips would you like to read about in the future? Share your comments, feedback and experiences with us by commenting below!

Leave a Comment

Back To Top