PHP Strings Primer - Parsing URLs
(Page 31 of 37 )
Earlier, we saw how to take an email address and parse it into its respective username and hostname parts. Fortunately, PHP provides built-in functionality for parsing URLs in the 'parse_url()' function. All we need to do is to pass it the URL, and it will break it down and return an associative array that we can easily work with. Let's look at some code that will demonstrate the different parts returned by this function.
<?php $url = "http://www.invaliddomain.ivd/dir1/script.php?var1=23"; $parts = parse_url ($url);
echo "scheme: {$parts['scheme']}<br /> host: {$parts['host']}<br /> path: {$parts['path']}<br /> query string: {$parts['query']}<br />"; ?> |
This would output:
scheme: http host: www.invaliddomain.ivd path: /dir1/script.php query string: var1=23 |
As you can see, this broke the URL down into several different pieces. This function will also return the user, password, and port number if it is included in the URL. Not only will this function work for http, but ftp and other schemes as well. Keep in mind, however, that this function is not meant to validate a URL, but to simply break it down.
Next: Encoding for URLs >>
More Programming Basics Articles
More By Matt Wade