PHPackages                             seborromeo/path-to-regex - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. seborromeo/path-to-regex

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

seborromeo/path-to-regex
========================

A PHP port of the js library path-to-regexp.

v1.0.0(1w ago)02MITPHPPHP ^8.1CI passing

Since Feb 18Pushed 1w agoCompare

[ Source](https://github.com/SeBorromeo/path-to-regex)[ Packagist](https://packagist.org/packages/seborromeo/path-to-regex)[ RSS](/packages/seborromeo-path-to-regex/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (2)Dependencies (2)Versions (4)Used By (0)

Path-to-Regex (PHP)
===================

[](#path-to-regex-php)

A PHP port of the JavaScript library [path-to-regexp](https://github.com/pillarjs/path-to-regexp).

> Turn a path string such as /user/:name into a regular expression.

Installation
------------

[](#installation)

```
composer require seborromeo/path-to-regex

```

Usage
-----

[](#usage)

```
use SeBorromeo\PathToRegex\PathToRegex;
```

### Parameters

[](#parameters)

Parameters match arbitrary strings in a path by matching up to the end of the segment, or up to any proceeding tokens. They are defined by prefixing a colon to the parameter name (`:foo`). Parameter names can use any valid JavaScript identifier, or be double quoted to use other characters (`:"param-name"`).

```
$fn = PathToRegex::match('/:foo/:bar');

$result = $fn('/test/route');
// [ 'path' => '/test/route', 'params' => [ 'foo' => 'test', 'bar' => 'route' ]]
```

### Wildcard

[](#wildcard)

Wildcard parameters match one or more characters across multiple segments. They are defined the same way as regular parameters, but are prefixed with an asterisk (`*foo`).

```
$fn = PathToRegex::match('/*splat');

$result = $fn('/bar/baz');
// ['path' => '/bar/baz', 'splat' => [ 'bar', 'baz' ]]
```

### Optional

[](#optional)

Braces can be used to define parts of the path that are optional.

```
$fn = PathToRegex::match('/users{/:id}/delete');

$result = $fn('/users/delete');
// [ 'path' => '/users/delete', 'params' => []]

$result = $fn("/users/123/delete");
// [ 'path' => '/users/123/delete', 'params' => ['id' => '123']]
```

Match
-----

[](#match)

The `match` function returns a function for matching strings against a path:

- **path** String, `TokenData` object, or array of strings and `TokenData` objects.
- **options** *(optional)* (Extends [pathToRegex](#pathToRegex) options)
    - **decode** Function for decoding strings to params, or `false` to disable all processing. (default: `PathToRegex::decodeURIComponent`)

```
$fn = PathToRegex::match('/:foo/:bar');
```

**Please note:** `path-to-regex` is intended for ordered data (e.g. paths, hosts). It can not handle arbitrarily ordered data (e.g. query strings, URL fragments, JSON, etc).

PathToRegex
-----------

[](#pathtoregex)

The `pathToRegex` function returns the `Regex` for matching strings against paths, and an array of `keys` for understanding the `Regex` matches.

- **path** String, `TokenData` object, or array of strings and `TokenData` objects.
- **options** *(optional)* (See [parse](#parse) for more options)
    - **sensitive** Regex will be case sensitive. (default: `false`)
    - **end** Validate the match reaches the end of the string. (default: `true`)
    - **delimiter** The default delimiter for segments, e.g. `[^/]` for `:named` parameters. (default: `'/'`)
    - **trailing** Allows optional trailing delimiter to match. (default: `true`)

```
['regex' => $regex, 'keys' => $keys] = PathToRegex::pathToRegex('/:foo/:bar');

preg_match($regex, '/foo/123', $matches);
// $matches = ['/foo/123', '123']
```

Compile ("Reverse" Path-To-Regex)
---------------------------------

[](#compile-reverse-path-to-regex)

The `compile` function will return a function for transforming parameters into a valid path:

- **path** A string or `TokenData` object.
- **options** (See [parse](#parse) for more options)
    - **delimiter** The default delimiter for segments, e.g. `[^/]` for `:named` parameters. (default: `'/'`)
    - **encode** Function for encoding input strings for output into the path, or `false` to disable entirely. (default: `rawurlencode`)

```
$toPath = PathToRegex::compile('/user/:id');

$toPath(['id' => 'name']); //=> '/user/name'
$toPath(['id' => 'café']); //=> '/user/caf%C3%A9'

$toPathRepeated = PathToRegex::compile('/*segment');

$toPathRepeated(['segment' => ['foo']]); //=> '/foo'
$toPathRepeated(['segment' => ['a', 'b', 'c']]); //=> '/a/b/c'

// When disabling `encode`, you need to make sure inputs are encoded correctly. No arrays are accepted.
$toPathRaw = PathToRegex::compile('/user/:id', ['encode' => false]);

$toPathRaw(['id' => '%3A%2F']); //=> '/user/%3A%2F'
```

Stringify
---------

[](#stringify)

Transform a `TokenData` object to a path string.

- **data** A `TokenData` object.

```
$data = new TokenData([
  new Text('/'),
  new Parameter('foo')
]);

$path = PathToRegex::stringify($data); //=> "/:foo"
```

Developers
----------

[](#developers)

- If you are rewriting paths with match and compile, consider using `'encode' => false` and `'decode' => false` to keep raw paths passed around.

### Parse

[](#parse)

The `parse` function accepts a string and returns `TokenData`, which can be used with `match` and `compile`.

- **path** A string.
- **options** *(optional)*
    - **encodePath** A function for encoding input strings. (default: `x => x`)

### Tokens

[](#tokens)

`TokenData` has two properties:

- **tokens** A sequence of tokens, currently of types `text`, `param`, `wildcard`, or `group`.
- **originalPath** The original path used with `parse`, shown in error messages to assist debugging.

### Custom path

[](#custom-path)

In some applications you may not be able to use the `path-to-regex` syntax, but you still want to use this library for `match` and `compile`. For example:

```
$path = new TokenData(
    tokens: [
        new Text('/'),
        new Parameter('foo'),
    ],
    originalPath: '/[foo]' // To help debug error messages.
);

$fn = PathToRegex::match($path);

$result = $fn('/test'); //=> ['path' => '/test', 'params' => ['foo' => 'test']]
```

Errors
------

[](#errors)

Common errors that might arise.

### Missing parameter name

[](#missing-parameter-name)

Parameter names must be provided after `:` or `*`, for example `/*path`. They can be valid JavaScript identifiers (e.g. `:myName`) or JSON strings (`:"my-name"`).

### Unexpected `?` or `+`

[](#unexpected--or-)

In past releases of the original JS library pillarjs/path-to-regexp, `?`, `*`, and `+` were used to denote optional or repeating parameters. As an alternative, try these:

- For optional (`?`), use braces: `/file{.:ext}`.
- For one or more (`+`), use a wildcard: `/*path`.
- For zero or more (`*`), use both: `/files{/*path}`.

### Unexpected `(`, `)`, `[`, `]`, etc.

[](#unexpected-----etc)

To avoid confusion, these characters have been reserved to avoid ambiguity. To match these characters literally, escape them with a backslash, e.g. `"\\("`.

### Unterminated quote

[](#unterminated-quote)

Parameter names can be wrapped in double quote characters, and this error means you forgot to close the quote character. For example, `:"foo`.

Compatibility
-------------

[](#compatibility)

This library aims to closely follow the behavior of pillarjs/path-to-regexp for parsing, matching, compiling, and tokenization.

License
-------

[](#license)

MIT

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance98

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~40 days

Total

3

Last Release

11d ago

Major Versions

v0.1.2-alpha → v1.0.02026-05-08

PHP version history (2 changes)v0.1.1-alphaPHP ^8.5

v0.1.2-alphaPHP ^8.1

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/103797945?v=4)[Sebastian Borromeo](/maintainers/SeBorromeo)[@SeBorromeo](https://github.com/SeBorromeo)

---

Top Contributors

[![SeBorromeo](https://avatars.githubusercontent.com/u/103797945?v=4)](https://github.com/SeBorromeo "SeBorromeo (23 commits)")

---

Tags

path-to-regexpphp-libraryrouter

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/seborromeo-path-to-regex/health.svg)

```
[![Health](https://phpackages.com/badges/seborromeo-path-to-regex/health.svg)](https://phpackages.com/packages/seborromeo-path-to-regex)
```

PHPackages © 2026

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