Skip to content

Instantly share code, notes, and snippets.

@imranismail
Last active September 17, 2015 10:43
Embed
What would you like to do?
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