PHP | strtr() for replacing substrings

It replaces given substring in a string with another given string. We can also use it to do multiple replacements by passing an array of pairs.

Examples:

Input : $str = "Hmrrb GmmksfbrGmmks";
        $from = "rbm";
        $to = "loe";
Output : Hello GeeksforGeeks

Input : $str = "Hello world";
        $arr = array("Hello" => "I Love", "world" => "GeeksforGeeks");
Output : I Love GeeksforGeeks

Syntax :

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

OR

string strtr (string $string, array $from_to_pairs)

Parameters :This function accepts three/two parameters and all of them are mandatory to be passed.
   Syntax 1 :
      1. $string: This parameter represents the given input string.
      2. $from: This parameter represents the sub string that is to be translated.
      3. $to: This parameter represents the translated sub string of “from” sub string.
   Syntax 2 :
      1. $string: This parameter represents the given input string.
      2. $translating_pairs: This parameter represents the array containing respective From-to pairs.

Return Value :This function returns a string in which all the characters of from sub string are replaced by to sub string in the given string.

Note that, if from and to have different lengths, then output will be co-related with that of the shortest.
Below programs illustrates the strtr() function in PHP:

Program 1 :

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
   
// original string
$str = "GzzksworGzzks is zverything.";
   
// from and to terms
$from = "zw";
$to = "ef";
  
// calling strtr() function
$resStr = strtr($str, $from, $to);
   
print_r($resStr);
   
?>

chevron_right


Output :

GeeksforGeeks is everything.

Program 2 :

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
   
// original string
$str = "Hi there";
   
// array declaring from-to pairs
$arr = array("Hi" => "Be", "there" => "Happy");
  
// calling strtr() function
$resStr = strtr($str, $arr);
   
print_r($resStr);
   
?>

chevron_right


Output :

Be Happy

Reference : http://php.net/manual/en/function.strtr.php



My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.