strtr
Replaces several substrings in a single pass.
Syntax
strtr(string $string, array $replace_pairs): stringParameters
| Parameter | Type | Description |
|---|---|---|
| $string | string | The source string. |
| $replace_pairs | array | An array of "what to replace => with what". |
Return value
stringThe string with the replacements.
Examples
Filling a template with values:
<?php
echo strtr('Hello, {name}! You are {age}.', ['{name}' => 'Anna', '{age}' => 25]);Output:
Hello, Anna! You are 25.Text that was already replaced is not replaced again:
<?php
echo strtr('ab', ['a' => 'b', 'b' => 'a']), "\n";
echo str_replace(['a', 'b'], ['b', 'a'], 'ab');Output:
ba
aaNotes
Unlike str_replace(), the replacements do not stack on top of each other — which makes strtr() more reliable for templates.
See also
- str_replace — Replaces all occurrences of a substring with another string.
In the tutorial
- Strings — Working with strings in PHP — quotes, concatenation, length, searching, replacing and multibyte functions.