string_interpolate
Format output strings
Definition
string string_interpolate(string $input, array|object $tokenParameters)
For a string input with marked placeholders, called positional tokens, inserts $tokenParameters
into the placeholders.
Parameters
string $input
String with positional tokens. If $tokenParameters
is an array, positional tokens are of the form {n}
, where n
is the index of the element of $tokenParameters
to be inserted in the positional token. If $tokenParameters
is an object, the format is {key}
, which inserts the value assigned to key
in $tokenParameters
.
array|object $tokenParameters
Array or object with data to be inserted into positional tokens inside input.
Returns
string
The string $input
with positional tokens replaced with $tokenParameters
.
Examples
{
a: string_interpolate('Hello, {0}!', ['World']),
b: string_interpolate('Hello, {0}! I\'m {1}. {2}', ['World', 'Alice']),
c: string_interpolate('Hello, {name}!', {"name": 'World'}),
d: string_interpolate('Hello, {name}! I\'m {sender}. {greeting}', {"name": 'World', "sender": 'Alice'})
}
{
"a": "Hello, World!",
"b": "Hello, World! I'm Alice. {2}",
"c": "Hello, World!",
"d": "Hello, World! I'm Alice. {greeting}"
}
Updated about 1 year ago