Oihana PHP

format.php

Table of Contents

Functions

format()  : string
Format a template string using an external document.

Functions

format()

Format a template string using an external document.

format(string $template, array<string|int, mixed>|object|string $document[, string $prefix = '{{' ][, string $suffix = '}}' ][, string $separator = '.' ][, string|null $pattern = null ][, bool $preserveMissing = false ]) : string

This function supports different types of documents:

  • If the document is a string, it replaces all placeholders with that string.
  • If the document is an array or object, it replaces placeholders by key lookup.
Parameters
$template : string

The string to format.

$document : array<string|int, mixed>|object|string

Key-value pairs for placeholders.

$prefix : string = '{{'

Placeholder prefix (default {{).

$suffix : string = '}}'

Placeholder suffix (default }}).

$separator : string = '.'

Separator used to traverse nested keys (default .).

$pattern : string|null = null

Optional full regex pattern to match placeholders (including delimiters).

$preserveMissing : bool = false
Tags
author

Marc Alcaraz (ekameleon)

since
1.0.0
example
use function oihana\core\strings\format;

// Using an array document
echo format('Hello, {{name}}!', ['name' => 'Alice']);
// Output: 'Hello, Alice!'

// Using nested keys with separator
echo format('ZIP: {{user.address.zip}}',
[
   'user' => ['address' => ['zip' => '75000']]
]);
// Output: 'ZIP: 75000'

// Using a custom prefix and suffix
echo format( 'Today is [[day]]' , ['day' => 'Monday'] , '[[' , ']]' ) ;
// Output: 'Today is Monday'

// Using a full custom regex pattern
$template = 'Hello, <<name>>!' ;
$doc      = ['name' => 'Alice'] ;
$pattern  = '/<<(.+?)>>/' ;
echo format($template, $doc, '<<', '>>', '.', $pattern);
// Output: 'Hello, Alice!'

// Using a string document: all placeholders replaced by same string
echo format( 'User: {{name}}, Role: {{role}}', 'anonymous');
// Ou
Return values
string

The formatted string.


        
On this page

Search results