strtr()
Introduction
The strtr() function in PHP translates substrings within a string. It is particularly useful for text processing where specific sequences need to be replaced efficiently. This article covers its syntax, behavior, and practical usage.
Understanding the strtr() function
The strtr() function supports two signatures:
Array signature
strtr(string $str, array $replace) : stringHere, $str is the input string and $replace is an associative array mapping substrings to their replacements. The function replaces all occurrences of the keys with their corresponding values.
Three-argument signature
strtr(string $str, string $from, string $to) : stringIn this form, $from and $to must be the same length. Each character in $from is mapped to the character at the same position in $to.
Important behavior: strtr() replaces substrings using a longest-match-first algorithm. This means overlapping patterns are resolved by prioritizing the longest match, and replacements are not applied recursively to the output.
Example Usage
Here is an example usage of the strtr() function in PHP:
Example of PHP strtr()
<?php
$string = "Hello World!";
$translation_rules = array("H" => "J", "W" => "Z");
$translated_string = strtr($string, $translation_rules);
echo $translated_string;In the example above, we define a string $string and an associative array $translation_rules. The strtr() function replaces the specified substrings ("H" and "W") with their mapped values ("J" and "Z"). Note that strtr() handles multi-character substrings and applies replacements in a single pass without recursion.
Conclusion
The strtr() function provides an efficient way to translate substrings in PHP. It supports both array-based mapping and character-by-character translation via the three-argument signature. Because it operates in a single pass using longest-match-first logic, it is generally faster than str_replace() for multiple replacements. Understanding these behaviors helps developers choose the right tool for text processing tasks.
Practice
What is the purpose of the strtr function in PHP?