crwlr/url - The Swiss Army Knife for Urls
This package is for you when PHP's parse_url() is not enough.
- Parse a url and access or modify all its components separately.
- Resolve any relative reference you may find in an HTML document to an absolute url, based on the document's url.
- Get not only the full host of a url, but also the registrable domain, the domain suffix and the subdomain parts of the host separately (Thanks to the Mozilla Public Suffix List).
- Compare urls or components of urls (e.g. checking if different urls point to the same host or domain)
- Thanks to symfony/polyfill-intl-idn it's also no problem to parse internationalized domain names (IDN).
- Includes an adapter class which implements the PSR-7 UriInterface.
Requires PHP version 7.2 or above.
Install the latest version with:
composer require crwlr/url
Including the package
<?php include('vendor/autoload.php'); use Crwlr\Url\Url;
To start using the library include composer's autoload file and import the Url class so you don't have to write the full namespace path again and again. Further code examples skip the above.
Parsing a url is easy as pie:
$url = Url::parse('https://john:firstname.lastname@example.org:8080/foo?bar=baz');
parse method of the
Url class provides a convenient way to
create a new instance and then access all of it's components separately.
// Accessing url components via method calls $port = $url->port(); // => 8080 $domainSuffix = $url->domainSuffix(); // => "com" $path = $url->path(); // => "/foo" $fragment = $url->fragment(); // => NULL // Or as properties $scheme = $url->scheme; // => "https" $user = $url->user; // => "john" $host = $url->host; // => "www.example.com" $domain = $url->domain; // => "example.com"
Of course you can also get a new instance using the
$url = new Url('https://www.steve.jobs/');
New in v1.0 of this package is, that you can obtain an instance of
a relative url as well. Previous versions throw an
the url string doesn't contain a valid scheme component.
$url = Url::parse('/some/path?query=string'); var_dump($url->__toString()); // => '/some/path?query=string' var_dump($url->scheme()); // => null var_dump($url->path()); // => '/some/path'