Translating characters and substrings

The strtr( ) function translates characters or substrings in a subject string:

string strtr(string subject, string from, string to)
string strtr(string subject, array map)

Search and replace with strtr function

When called with three arguments, strtr( ) translates the characters in the subject string that match those in the from string with the corresponding characters in the to string. When called with two arguments, a subject string and an array map, occurrences of the map keys in subject are replaced with the corresponding map values.

If given three arguments, this function returns a copy of str where all occurrences of each (single-byte) character in from have been translated to the corresponding character, if from and to have different lengths, the extra characters in the longer of the two are ignored. The length of str will be the same as the return value's. The following example uses strtr( ) to replace all lowercase vowels with the corresponding umlauted character:

$mischief = strtr("", "aeiou", "");
print $mischief;  // prints

If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values.

When an associative array is passed as a translation map, strtr( ) replaces substrings rather than characters. The following example shows how strtr( ) can expand acronyms:

string strtr(string subject, array map)
// Short list of acronyms used in e-mail
$glossary = array("BTW"=>"by the way",
                  "IMHO"=>"in my humble opinion",
                  "IOW"=>"in other words",
                  "OTOH"=>"on the other hand");
// Maybe now I can understand
print strtr($geekMail, $glossary);