composer require weew/url
Currently this library is able to parse and build urls of such format and complexity:
// protocol://username:[email protected]:port/path?key=value#fragment
For example:
// https://john:[email protected]:8080/my/path?query=value&some=value#hashtag
Creating a new url is very easy:
$url = new Url('http://username:[email protected]:80/some/path?query=value#fragment');
Url containts manny segments which can be accessed trough convenient methods:
echo $url->getProtocol();
// http
echo $url->getHost();
// subdomain.domain.com
echo $url->getDomain();
// domain
echo $url->getSubdomain();
// subdomain
echo $url->getTLD();
// com
echo $url->getPort();
// 80
echo $url->getPath();
// /some/path
echo $url->getQuery();
// query=value
echo $url->getFragment();
// fragment
echo $url->getUsername();
// username
echo $url->getPassword();
// password
You can modify url segments in the same manner.
$url->setProtocol('https');
$url->setHost('another.domain.net');
// or
$url->setDomain('domain');
$url->setSubdomain('another');
$url->setTLD('net');
$url->setPort(8080);
$url->setPath('my/path');
$url->addPath('here');
$url->getQuery()->set('some', 'value');
$url->setFragment('hashtag');
$url->setUsername('john');
$url->setPassword('doe');
echo $url;
// https://john:[email protected]:8080/my/path/here?query=value&some=value#hashtag
You can match url path against a pattern.
$url = new Url('users/1');
// true
$url->match('users/{id}');
$url = new Url('users');
// false
$url->match('users/{id}');
Placeholders can be optional by adding the ?
sign at the end.
$url = new Url('users/1');
// true
$url->match('users/{id?}');
$url = new Url('users');
// true
$url->match('users/{id?}');
Placeholders can have custom patterns.
$url = new Url('users/1');
// true
$url->match('users/{id}', [
'id' => '[0-9]+',
]);
$url = new Url('users/abc');
// false
$url->match('users/{id}', [
'id' => '[0-9]+',
]);
For further documentation check out the weew/url-matcher package;
Retrieving placeholder values is very trivial.
$url = new Url('users/1');
$dictionary = $url->parse('users/{id}');
// 1
$dictionary->get('id');
For further documentation check out the weew/url-matcher package;
You can replace placeholders inside your path with values.
$url = new Url('{subdomain}.service.com/users/{id}/profile');
$url->replace('subdomain', 'api');
$url->replace('id', 1);
// or
$url->replaceAll(['subdomain' => 'api', 'id' => 1]);
// api.service.com/users/1/profile
$url->toString();