[Previous] [Contents] [Next]


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)

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.

The following example uses strtr( ) to replace all lowercase vowels with the corresponding umlauted character:

$mischief = strtr("command.com", "aeiou", "äëïöü");
print $mischief;  // prints cömmänd.cöm

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:

// 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);

[Previous] [Contents] [Next]