PHP Reference ยท String Functions
PHP strtr() function
Reference for PHP strtr(): translate single characters or replace many substrings at once, longest match first, with examples and pitfalls.
strtr() has two forms. With three arguments it translates characters one for one: every character found in $from is replaced by the character at the same position in $to. With two arguments it takes an array of substring pairs and replaces them all in a single pass.
The array form is the tool to reach for when replacements must not affect each other. It always tries the longest key first and never scans text it has already replaced, unlike an array passed to str_replace().
<?php echo strtr("hello", "el", "ip"); // hippo echo strtr("Hi all", ["Hi" => "Hello", "all" => "world"]); // Hello world
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
strtr(string $string, string $from, string $to): string strtr(string $string, array $replace_pairs): string
| Name | Description |
|---|---|
$string |
The input string. |
$from |
Characters to replace (three-argument form). |
$to |
Replacement characters, matched by position. If one is longer, the extra characters are ignored. |
$replace_pairs |
Array of "search" => "replacement" pairs (two-argument form). |
Return value: the translated string. If $replace_pairs is empty, the original string is returned.
Usage notes
- Single pass. In the array form, text produced by a replacement is never searched again, so
["a" => "b", "b" => "a"]swaps the letters cleanly. - Longest key first, regardless of the order in the array.
- Case-sensitive. There is no case-insensitive variant.
- Bytes, not characters. The three-argument form works on bytes, so it is not suitable for multibyte UTF-8 letters. The array form is fine with UTF-8 because it matches whole substrings.
- Empty keys are not allowed: an empty-string key is ignored with a warning.
- Integer keys are converted to strings, and values are converted to strings too.
- Handy for templates with placeholders, as in the second example, but it does not escape values.
- Good for removing accents in a custom map or for swapping delimiters.