Last active
September 17, 2015 10:43
-
-
Save imranismail/8e666cef9dc4378e4dec to your computer and use it in GitHub Desktop.
UrlParser.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class UrlParser | |
{ | |
/** | |
* The url to be parsed | |
* @param String $url | |
*/ | |
public function __construct($url) | |
{ | |
if ($this->validate($url)) | |
{ | |
$this->url = $this->parse_url($url); | |
} | |
} | |
/** | |
* Get the component of a passed URL, if none passed returns everything | |
* @param String $component options are as below | |
* ['scheme', 'host', 'port', 'user', 'pass', 'path', 'query', 'tld', 'subdomains'] | |
* @return Array component requested | |
*/ | |
public function get($component) | |
{ | |
if ($component === null) { | |
return $this->url; | |
} | |
return $this->url[$component]; | |
} | |
/** | |
* Validated passed URL | |
* @param String $url the url to validate | |
* @return Boolean true or false | |
*/ | |
private function validate($url) | |
{ | |
if (filter_var($url, FILTER_VALIDATE_URL) === false) { | |
throw new Exception("Invalid URL Provided"); | |
} | |
return true; | |
} | |
/** | |
* Advanced parser, added extra fields to the standard library | |
* @param String $url | |
* @return Array | |
*/ | |
private function parse_url($url) | |
{ | |
$components = parse_url($url); | |
$components['subdomains'] = explode('.', $components['host']); | |
$components['tld'] = array_pop($components['subdomains']); | |
return $components; | |
} | |
} | |
$url = new UrlParser("http://gmail.google.com"); | |
var_dump($url->get()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment