PHPackages                             innova2/url-builder - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. innova2/url-builder

ActiveLibrary

innova2/url-builder
===================

A lightweight PHP 7.4+ library with many features to easy build URLs

1.0.2(1y ago)21.1k↓33.3%1MITHTMLPHP &gt;=7.4.0CI failing

Since Apr 8Pushed 1y ago1 watchersCompare

[ Source](https://github.com/InnovA2/url-builder-php)[ Packagist](https://packagist.org/packages/innova2/url-builder)[ Docs](https://github.com/InnovA2/url-builder-php)[ RSS](/packages/innova2-url-builder/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (4)Versions (4)Used By (0)

Url-Builder
===========

[](#url-builder)

[![Coverage](coverage/badge.svg)](coverage/badge.svg)

A lightweight library with many features to easy build URLs

- [Features](#bookmark_tabs-features)
- [Installation](#hammer_and_wrench-installation)
- [Usage](#memo-usage)
    - [Create from existing URL](#create-from-existing-url)
    - [Handle path](#handle-path)
    - [Handle query param](#handle-query-param)
    - [Work with parent](#work-with-parent)
    - [Get relative path](#get-relative-path)
    - [Get query params in string](#get-query-params-in-string)
    - [Convert full URL to string](#convert-full-url-to-string)
- [Advanced](#memo-advanced)
    - [Compare URL to another](#compare-url-to-another)
    - [Get word between two others](#get-word-between-two-others)
    - [Split path from string (static)](#split-path-from-string-static)
    - [Trim path from string (static)](#trim-path-from-string-static)
- [API](#gear-api)
- [Licence](#balance_scale-licence)
- [Authors](#busts_in_silhouette-authors)
- [Contributors](#handshake-contributors)

📑 Features
----------

[](#bookmark_tabs-features)

This library allows :

- Create URLs most easly
- Parse and decompose your URLs
- Ride up in the URL tree
- Make comparisons between URLs

🛠️ Installation
---------------

[](#hammer_and_wrench-installation)

To import the library you just need to run this command :

```
composer require innova2/url-builder
```

📝 Usage
-------

[](#memo-usage)

### Create from existing URL

[](#create-from-existing-url)

```
$url = UrlBuilder::createFromUrl('http://localhost:8080/users');
// or create new url with the constructor
```

### Handle path

[](#handle-path)

Add new path segment(s)

```
$userId = '170b16cd-ad47-4c9c-86cf-7c83bd40d775';
$url->addPath(':id/comments')->addParam('id', $userId);
```

Add multiples parameters

```
$userId = '170b16cd-ad47-4c9c-86cf-7c83bd40d775';
$commentId = '218dd1c4-0bb0-425a-be0b-85427304e100';
$url->addPath(':userId/comments/:commentId')->addParams([
    'userId' => $userId,
    'commentId' => $commentId
]);
```

Get the first path segment

```
$rowNum = 10;
$url = UrlBuilder::createFromUrl('http://localhost:8080/rows/:rowNum/cells')->addParam('rowNum', $rowNum);
$url->getFirstPath(); // Output: 'rows'
```

Get the last path segment

```
$url->getLastPath(); // Output: 'cells'
```

### Handle query param

[](#handle-query-param)

Add new query param

```
$page = 2;
$url->addQuery('page', $page);
```

Add multiples query params

```
$page = 2;
$order = 'DESC';
$url->addQueries([
    'page' => $page,
    'order' => $order
]);
```

### Work with parent

[](#work-with-parent)

Get parent URL easly.
*This function return a new instance of UrlBuilder*

```
$url = UrlBuilder::createFromUrl('http://localhost:8080/orders/:orderId/products/:productId');
$parent = $url->getParent(); // Get 'http://localhost:8080/orders/:orderId/products'
```

Or up to the specific level

```
$url->getParent(3); // Get 'http://localhost:8080/orders'
```

### Get relative path

[](#get-relative-path)

Retrieve the relative path in string format

```
$postId = 'a937b39e-9664-404a-ac56-f3da2b83a951';
$url = UrlBuilder::createFromUrl('http://localhost:8080/posts/:id')->addParam('id', $postId);
$url->getRelativePath(); // Output: '/posts/a937b39e-9664-404a-ac56-f3da2b83a951'
```

And with query params
*Don't forget to add 'true' parameter to allow query params conversion*

```
$url->addQuery('displaySimilar', true);
$url->getRelativePath(); // Output: '/posts/a937b39e-9664-404a-ac56-f3da2b83a951'
$url->getRelativePath(true); // Output: '/posts/a937b39e-9664-404a-ac56-f3da2b83a951?displaySimilar=true'
```

### Get query params in string

[](#get-query-params-in-string)

Retrieve the query params in string format

```
$url = UrlBuilder::createFromUrl('http://localhost:8080/vehicles')->addQueries([
  'page' => '2',
  'order' => 'ASC'
]);
$url->getQueryString(); // Output: '?page=2&order=ASC'
```

### Convert full URL to string

[](#convert-full-url-to-string)

Retrieve the query params in string format

```
$name = 'url-builder';
$url = UrlBuilder::createFromUrl('https://github.com/InnovA2')
        ->addPath(':name/pulls')
        ->addParam('name', $name);
$url->toString(); // Output: 'https://github.com/InnovA2/url-builder/pulls'
```

📝 Advanced
----------

[](#memo-advanced)

### Compare URL to another

[](#compare-url-to-another)

Compare the current URL to another URL (UrlBuilder instance)

```
$id = '434f65eb-4e5f-4b29-899c-b3e159fff61c';
$id2 = '3e972ca2-b422-4ac9-b793-e6f305c7bfb2';
$url = UrlBuilder::createFromUrl('http://localhost:8080/users/:id')->addParam('id', $id);
$url2 = UrlBuilder::createFromUrl('http://localhost:8080/users/:id')->addParam('id', $id);
$url3 = UrlBuilder::createFromUrl('http://localhost:8080/users/:id')->addParam('id', $id2);
$url->compareTo($url2); // Output: true
$url->compareTo($url3); // Output: false
```

### Get word between two others

[](#get-word-between-two-others)

Compare the current URL to another URL (UrlBuilder instance)

```
$id = '434f65eb-4e5f-4b29-899c-b3e159fff61c';
$url = UrlBuilder::createFromUrl('http://localhost:8080/users/:id')->addParam('id', $id);
$url->compareTo($url2); // Output: true
$url->compareTo($url3); // Output: false
```

### Split path from string (static)

[](#split-path-from-string-static)

Split path string by slash

```
UrlBuilder::splitPath('/InnovA2/url-builder/pulls/'); // Output: ['InnovA2', 'url-builder', 'pulls']
// or if you have more slashes
UrlBuilder::splitPath('/InnovA2///url-builder/pulls/'); // Output: ['InnovA2', 'url-builder', 'pulls']
```

### Trim path from string (static)

[](#trim-path-from-string-static)

Trim path string by removing useless slashes

```
UrlBuilder->trimPath('/InnovA2/url-builder/pulls/'); // Output: 'InnovA2/url-builder/pulls'
// or if you have more slashes
UrlBuilder->trimPath('/InnovA2///url-builder/pulls/'); // Output: 'InnovA2/url-builder/pulls'
```

⚙️ API
------

[](#gear-api)

```
static function createFromUrl(string $baseUrl): UrlBuilder
static function splitPath(string $path): array
static function trimPath(string $path): string
function compareTo(UrlBuilder $url, bool $relative = true): bool
function getScheme(): string
function getHost(): string
function getPort(): int
function getPaths(): array
function setPort(int $port): UrlBuilder
function addPath(string $path): UrlBuilder
function addParam(string $key, $value): UrlBuilder
function addParams(array $params): UrlBuilder
function getParams(): array
function addQuery(string $key, $value): UrlBuilder
function addQueries(array $queries): UrlBuilder
function getQuery(): array
function getFirstPath(): string
function getLastPath(): string
function getParent(int $n = 1): UrlBuilder
function getBetween2Words(string $a, string $b): ?string
function getRelativePath(bool $query = false): string
function getQueryString(): ?string
function toString(): string
```

⚖️ Licence
----------

[](#balance_scale-licence)

[MIT](LICENSE)

👥 Authors
---------

[](#busts_in_silhouette-authors)

- [Adrien MARTINEAU](https://github.com/WaZeR-Adrien)
- [Angéline TOUSSAINT](https://github.com/AngelineToussaint)

🤝 Contributors
--------------

[](#handshake-contributors)

Do not hesitate to participate in the project! Contributors list will be displayed below.

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance36

Infrequent updates — may be unmaintained

Popularity21

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 54.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~641 days

Total

3

Last Release

584d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/890622?v=4)[AdrienM](/maintainers/AdrienM)[@AdrienM](https://github.com/AdrienM)

---

Top Contributors

[![WaZeR-Adrien](https://avatars.githubusercontent.com/u/8389829?v=4)](https://github.com/WaZeR-Adrien "WaZeR-Adrien (6 commits)")[![AngelineToussaint](https://avatars.githubusercontent.com/u/39911545?v=4)](https://github.com/AngelineToussaint "AngelineToussaint (4 commits)")[![tombohub](https://avatars.githubusercontent.com/u/3029412?v=4)](https://github.com/tombohub "tombohub (1 commits)")

---

Tags

urluristringconstructroutingpathquerybuilderparserouteurl builderbuildparamsconcatqueryparamurlbuilder

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/innova2-url-builder/health.svg)

```
[![Health](https://phpackages.com/badges/innova2-url-builder/health.svg)](https://phpackages.com/packages/innova2-url-builder)
```

###  Alternatives

[symfony/routing

Maps an HTTP request to a set of configuration variables

7.6k789.4M1.8k](/packages/symfony-routing)[league/uri-components

URI components manipulation library

31932.3M67](/packages/league-uri-components)[miladrahimi/phprouter

A powerful, lightweight, and very fast HTTP URL router for PHP projects.

20832.6k2](/packages/miladrahimi-phprouter)[crwlr/url

Swiss Army knife for URLs.

11073.3k3](/packages/crwlr-url)[illuminatech/url-trailing-slash

Allows enforcing URL routes with or without trailing slash

50216.9k](/packages/illuminatech-url-trailing-slash)[josantonius/url

PHP library to access URL information.

123.2k2](/packages/josantonius-url)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
