PHP strtr() Function

PHP strtr() Function

The strtr() function in PHP translates or replaces certain characters in a string.

Syntax

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

or

strtr ( string $str , array $replace_pairs )

Parameter

str(required)- This parameter specifies the string to translate

from(required)- This parameter represents the string being translated to the parameter ‘to’.

to(required)- It specifies what characters to change.

replace_pairs(optional)- This parameter signifies an array containing what to change from as key, and what to change to as value.

Return

This function returns the translated string. If the replace_pairs parameter contains a key which is an empty string (""), it will return FALSE.

Example 1

 

Output

Original string: Lulla Warld
 After the strtr() function...
 New string: Hello World 

Example 2

 "!", "hello" => "Hi", "hi" => "Hello");
 echo("\nAfter the strtr() function...");
 echo "\nNew string: ".strtr($str, $val);
 ?> 

Output

Actual string: hi World@ hello PHP
After the strtr() function...
New string: Hello World! Hi PHP 

Example 3

 

Output

Original string: Lulla Warld
After the strtr() function...
New string: Lulla Warld 

Example 4

 "L@");
 echo strtr($str, $trans);
 ?> 

Output

I Love PHP language
I L@ve PHP language