weew/url

简单的URL包装器。

v2.2.0 2017-02-22 17:29 UTC

README

Build Status Code Quality Test Coverage Dependencies Version Licence

目录

安装

composer require weew/url

概述

目前这个库能够解析和构建如下格式和复杂性的URL

// protocol://username:password@subdomain.domain.tld:port/path?key=value#fragment

例如

// https://john:doe@another.domain.net:8080/my/path?query=value&some=value#hashtag

实例化

创建一个新的URL非常简单

$url = new Url('http://username:password@subdomain.domain.com:80/some/path?query=value#fragment');

解析

URL包含多个段,可以通过方便的方法访问

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

构建

您可以使用相同的方式修改URL段。

$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:doe@another.domain.net:8080/my/path/here?query=value&some=value#hashtag

匹配

您可以将URL路径与模式进行匹配。

$url = new Url('users/1');
// true
$url->match('users/{id}');

$url = new Url('users');
// false
$url->match('users/{id}');

可以通过在末尾添加?符号使占位符为可选。

$url = new Url('users/1');
// true
$url->match('users/{id?}');

$url = new Url('users');
// true
$url->match('users/{id?}');

占位符可以有自定义的模式。

$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]+',
]);

有关进一步文档,请查看weew/url-matcher包;

解析

检索占位符值非常简单。

$url = new Url('users/1');
$dictionary = $url->parse('users/{id}');
// 1
$dictionary->get('id');

有关进一步文档,请查看weew/url-matcher包;

替换

您可以用值替换路径中的占位符。

$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();