Open In App

PHP | strtr() for replacing substrings

Improve
Improve
Like Article
Like
Save
Share
Report

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 :




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


Output :

GeeksforGeeks is everything.

Program 2 :




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


Output :

Be Happy

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



Last Updated : 26 May, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads