![]() |
VOOZH | about |
The strtr() is an inbuilt function in PHP which is used to replace a substring in a string to a given string of characters. It also has the option to change a particular word to a different word in a string. The function is case sensitive.
Syntax:
strtr($string, $string1, $string2) or, strtr($string, $arr)
Parameters: This function accepts three parameters as shown in the above syntax and described below:
Note: When $string1 and $string2 are of different length, then the longer string will be formatted to the length of the shorter one.
Return Value: The return value of this function depends on two cases:
Examples:
Input : $string = "gieuz foh geeks",
$string1 = "iuzh" , $string2="eksr"
Output : geeks for geeks
Explanation : i replaced by e
u replaced by k
z replaced by s
h replaced by r
Input : $string = "gieuz foh geeks",
$string1 = "iuzh" , $string2 = "eks"
Output : geeks foh geeks
Explanation: "iuzh" was reduced to "iuz" and then
replacement was done.
Input: $string = "giiks in giiks",
$arr = array("giiks" => "geeks", "in" => "for")
Output: geeks for geeks
Explanation: "giiks" was replaced by "geeks" and
"in" by "for"
Below programs illustrate the strtr() function in PHP:
Program 1: Program to demonstrate the strtr() function when same length string1 and string2 is passed.
Output:
geeks for geeks
Program 2: Program to demonstrate the strtr() function when different length string1 and string2 is passed.
Output:
geeks foh geeks
Program 3: Program to demonstrate the strtr() function which replaces at all positions where characters are present.
Output:
geeks for geeks
Program 4: Program to demonstrate the strtr() function when array is passed as the parameter.
Output:
geeks for geeks
Program 5: Program to demonstrate the strtr() function when one key in array is passed as "".
Output:
No Output