Replace characters or substrings with strtr()

Learn how to use strtr( ) function to translate characters and replace substrings in a given string.

 // 1. Three Arguments Syntax
 strtr(string $string, string $from, string $to): string

 // 2. Two Arguments Syntax
 strtr(string $string, array $replace_pairs): string

Translate a string with strtr()

The three arguments syntax is useful when you need to translate a string from one character set to another. The strtr( ) translates the characters in the input string $string that match those in the from string $from with the corresponding characters in the to string $to. See the following example:

 $string = "Welcome to";
 $from = 'abcdefghijklmnopqrstuvwxyz';
 echo strtr($string, $from, $to);

Example: Translate/replace space and dot with the hyphen and underscore

 $string = 'Welcome to';
 $from   = ' .';
 $to     = '-_';

 echo strtr($string, $from, $to);

Note: Using strtr() function, you can not replace multibyte characters with single-byte characters or vice-versa. Single-byte characters can replace with single-byte characters and multibyte characters can replace with multibyte characters:

 $str = 'äëïöü';
 echo strtr($str, 'ä', 'a');
 //Prints: a�a�a�a�a�

 echo strtr($str, 'ä', 'ë') ."\n";
 //Prints; ëëïöü

Replace substrings with strtr()

When called with two arguments, an input string $string and an array map $replace_pairs, occurrences of the map keys in the input string are replaced with the corresponding map values. The following example shows how strtr( ) can expand acronyms:

 $string = 'BTW, I saw you yesterday';
 $replace_pairs = [
   'BTW' =>'by the way',
   'FAQ'=>'frequently asked question',
   'IOW' =>'in other words',
   'TBH'=>'to be honest'

 echo strtr($string, $replace_pairs);
 //by the way, I saw you yesterday

When $replace_pairs associative array is passed as a translation map, strtr( ) replaces substrings rather than characters.

Manipulating substrings:

  1. Extracting a specific portion of string by position
  2. Searching positions of a substring in a string
  3. How many times a substring occurs in a string
  4. Extract text before or after the match
  5. Replace a portion of string by position
  6. Replace all occurrences of a string with str_replace()
  7. Replace characters or substrings with strtr()
  8. Find a given substring in the string
  9. Manipulating strings: change string case