Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

strtr

Replaces several substrings in a single pass.

Syntax

strtr(string $string, array $replace_pairs): string

Parameters

ParameterTypeDescription
$stringstringThe source string.
$replace_pairsarrayAn 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
aa

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.