Oihana PHP

formatFromDocument.php

Table of Contents

Functions

formatFromDocument()  : string
Format a template string using key-value pairs from an array or object.

Functions

formatFromDocument()

Format a template string using key-value pairs from an array or object.

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

This function replaces placeholders in the template with corresponding values found in the provided associative array or object. Placeholders are defined by a prefix and suffix (default {{ and }}), and keys can be nested using the separator (default .).

Parameters
$template : string

The string to format.

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

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

If true, preserves unresolved placeholders instead of removing them (default false).

Tags
author

Marc Alcaraz (ekameleon)

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

echo formatFromDocument('Hello, {{name}}!', ['name' => 'Alice']);
// Output: 'Hello, Alice!'

echo formatFromDocument('Today is [[day]]', ['day' => 'Monday'], '[[', ']]');
// Output: 'Today is Monday'

echo formatFromDocument('ZIP: {{user.address.zip}}', [
    'user' => ['address' => ['zip' => '75000']]
]);
// Output: 'ZIP: 75000'

Custom pattern example

$template = 'Hello, <<name>>!';
$doc = ['name' => 'Alice'];
$pattern = '/<<(.+?)>>/';
echo formatFromDocument($template, $doc, '<<', '>>', '.', $pattern);
// Output: 'Hello, Alice!'

Preserve unresolved placeholder

echo formatFromDocument
(
    'Hello, {{name}}! From {{country}}.',
    ['name' => 'Alice'] ,
    preserveMissiong: true
) ;
// Output: 'Hello, Alice! From {{country}}.'
Return values
string

The formatted string.


        
On this page

Search results