Categories
PHP

Replace characters or substrings with strtr()

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

<?php
 // 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:

 <?php
 $string = "Welcome to BrainBell.com";
 $from = 'abcdefghijklmnopqrstuvwxyz';
 $to   = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 
 echo strtr($string, $from, $to);
 //WELCOME TO BRAINBELL.COM

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

<?php
 $string = 'Welcome to BrainBell.com';
 $from   = ' .';
 $to     = '-_';

 echo strtr($string, $from, $to);
 //Welcome-to-BrainBell_com

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:

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

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

To solve this issue, use the two arguments syntax, for example:

<?php
 $str = 'äëïöü';
 $translation = array('ä'=>'a','ë'=>'e','ï'=>'i','ö'=>'o', 'ü'=>'u');
 echo strtr($str, $translation);
 //Prints: aeiou

See How to Find and Replace Unicode Accents.

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:

<?php
 $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: