Oihana PHP

replacePathPlaceholders.php

Table of Contents

Functions

replacePathPlaceholders()  : string
Replaces placeholders in a path string with values from an associative array.

Functions

replacePathPlaceholders()

Replaces placeholders in a path string with values from an associative array.

replacePathPlaceholders(string|null $path[, array<string|int, mixed> $args = [] ][, string $pattern = '/\{([a-zA-Z0-9_]+)(:[^}]+)?}/' ]) : string

Placeholders in the path are expected in one of the following forms:

  • {name} : simple placeholder.
  • {name:regex} : placeholder with an optional regex pattern.

If a value for a placeholder is not provided in $args, the placeholder remains unchanged in the output.

Examples

Simple replacement:

$path = '/observation/{observation}/workspace/{workspace}/places';
$args = ['observation' => '15454', 'workspace' => '787878'];
echo replacePathPlaceholders($path, $args);
// Output: '/observation/15454/workspace/787878/places'

Undefined placeholder fallback:

$path = '/foo/{missing}/bar';
$args = ['other' => 'value'];
echo replacePathPlaceholders($path, $args);
// Output: '/foo/{missing}/bar'  (placeholder stays unchanged)

Placeholder with regex:

$path = '/product/{product:[A-Za-z0-9_]+}/warehouse/{warehouse:[0-9]+}';
$args = ['product' => 'ABC123', 'warehouse' => '42'];
echo replacePathPlaceholders($path, $args);
// Output: '/product/ABC123/warehouse/42'

Custom regex pattern:

$path = '/foo/:bar/baz';
$args = ['bar' => '123'];
$pattern = '/:([a-zA-Z0-9_]+)/';
echo replacePathPlaceholders($path, $args, $pattern);
// Output: '/foo/123/baz'

Empty path or null:

echo replacePathPlaceholders(null); // Output: ''
echo replacePathPlaceholders('');   // Output: ''
Parameters
$path : string|null

The path containing placeholders, e.g., '/users/{id}'.

$args : array<string|int, mixed> = []

Associative array of placeholder values (key = placeholder name).

$pattern : string = '/\{([a-zA-Z0-9_]+)(:[^}]+)?}/'

Regex pattern to detect placeholders (default: '/{([a-zA-Z0-9_]+)(:[^}]+)?}/').

Tags
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
string

The path with placeholders replaced by their corresponding values.


        
On this page

Search results