URI parser and builder

The League\Uri\UriString class is a user-land PHP URI parser and builder compliant with RFC 3986 and RFC 3987 . This class is a drop-in replacement for PHP’s parse_url function.

URI parsing

UriString::parse(string $uri): array
UriString::parseAuthority(string $autority): array

The parser is:

<?php

use League\Uri\UriString;

var_export(UriString::parse('http://foo.com?@bar.com/#'));
//returns the following array
//array(
//  'scheme' => 'http',
//  'user' => null,
//  'pass' => null,
//  'host' => 'foo.com',
//  'port' => null,
//  'path' => '',
//  'query' => '@bar.com/',
//  'fragment' => '',
//);

Just like parse_url, the League\Uri\UriString only parses and extracts from the URI its components. Validating against scheme specific rules is still a requirement.

var_export(UriString::parse('http:www.example.com'));
//returns the following array
//array(
//  'scheme' => 'http',
//  'user' => null,
//  'pass' => null,
//  'host' => null,
//  'port' => null,
//  'path' => 'www.example.com',
//  'query' => null,
//  'fragment' => null,
//);

This invalid HTTP URI is successfully parsed.

The class also exposes a UriString::parseAuthority you can use to parse an authority string.

URI Building

UriString::build(array $components): string
UriString::buildAuthority(array $components): string

You can rebuild a URI from its hash representation returned by the UriString::parse method or PHP’s parse_url function using the UriString::build public static method.

If you supply your own hash you are responsible for providing valid encoded components without their URI delimiters.

$components = UriString::parse('http://hello:world@foo.com?@bar.com/');
//returns the following array
//array(
//  'scheme' => 'http',
//  'user' => 'hello',
//  'pass' => 'world',
//  'host' => 'foo.com',
//  'port' => null,
//  'path' => '',
//  'query' => '@bar.com/',
//  'fragment' => null,
//);

echo UriString::build($components); //displays http://hello:world@foo.com?@bar.com/

The build method provides similar functionality to the http_build_url() function from v1.x of the pecl_http PECL extension.

The class also exposes a UriString::buildAuthority you can use to build an authority from its hash representation.