Skip to content

Instantly share code, notes, and snippets.

@imranismail
Last active September 17, 2015 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imranismail/8e666cef9dc4378e4dec to your computer and use it in GitHub Desktop.
Save imranismail/8e666cef9dc4378e4dec to your computer and use it in GitHub Desktop.
UrlParser.php
<?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