strtr() Function Use in PHP 8.4 and PHP 8.5

strtr() behaves identically in PHP 8.4 and PHP 8.5. The official PHP documentation lists the function as available for PHP 8 generally, with no version-specific changes noted for these releases.

Function

strtr() translates characters or replaces substrings. It has two distinct modes of operation depending on how many arguments you pass.

Signatures:

// Mode 1: Byte-by-byte translation (3 arguments)
strtr(string $string, string $from, string $to): string

// Mode 2: Substring replacement (2 arguments, array)
strtr(string $string, array $replace_pairs): string

Examples

Example 1: Three Arguments (Character Translation) This mode replaces single characters based on their position. It is best for simple, single-byte character swaps.

<?php
$original = "He1Lo, w0rld!";

// Replaces 1 with l , L with l , and 0 with o
$result = strtr($original, "1L0", "llo");
echo $result;
// Outputs: Hello, world!
?>

Example 2: Two Arguments (Substring Replacement) This mode replaces keys with values in an array. It prioritizes longer keys and does not re-scan replaced text.

<?php
$replace_pairs = ["h" => "-", "hello" => "hi", "hi" => "hello"];
echo strtr("hi all, I said hello", $replace_pairs);
// Outputs: hello all, I said hi
?>

Note how "hello" is replaced by "hi", and "hi" is replaced by "hello", but the newly inserted "hello" is not changed back.

23 Views