The Wayback Machine - https://web.archive.org/web/20231211184119/https://www.geeksforgeeks.org/php-strtr-replacing-substrings/
Open In App
Related Articles

PHP | strtr() for replacing substrings

Improve Article
Improve
Save Article
Save
Like Article
Like

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


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 26 May, 2018
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials