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 :
<?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
Recommended Posts:
- PHP | strtr() Function
- Replacing spaces with underscores in JavaScript
- How to detect operating system on the client machine using JavaScript ?
- What is the difference between children and childNodes in JavaScript?
- 5 Must Have Tools For Web Application Penetration Testing
- How to create hash from string in JavaScript ?
- TCS Digital Interview through Codevita'19
- CSS | perspective() Function
- PHP | Imagick levelImage() Function
- Why Serverless Apps?
- BabyChakra Interview Experience
- How to create a custom callback in JavaScript?
- How to place the image above the slider in mobile view in bootstrap?
- How to get the same behavior with confirm and bootstrap modal?
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.




