strtr – PHP String Functions

String strtr ( string, from, to );

OR

String strtr ( string, replace_array );


Description :

It’s an inbuilt function of PHP. strtr() function translate characters or replace strings.

In case if array is passed, This function will be the most efficient when all the keys have the same size.

Note: If from and to parameters have different lengths, the extra characters in the longer of the two are ignored. The length of string will be the same as the return value’s.


Parameter :

[table caption=”” width=”100%” colwidth=”15%|15%|15%|55%” colalign=”left|left|left|left”]
Name, Required /Optional, Value Type, Description

string, Required, String, Main string to be translated.

from, Required(if array is not used)String, Characters which needs to be translated from.

to, Required(if array is not used)String,  Characters which needs to be changed to to.

replace_array, Required(if to and from is not used), Array, This parameter represents the array containing respective From-to pairs Example  array(‘from’ => ‘to’) n times.

[/table]


Output :

It returns a translated or replaced string. Or in other words string in which all the characters of from sub string are replaced by to sub string in the given string.

If the replace_array parameter contains a key which is an empty string (“”), it will return FALSE.


Related articles : str_replace() , substr_replace().


strtr() – PHP Functions Example 1 :
<?php
echo strtr("He froj Tutorhal.","ejh","imi");
?>

In above example, We have string “He froj Tutorhal.”. from string “ejh” is changed to “imi”. So, the output of above code in the browser is as below:

Hi from Tutorial

strtr() – PHP Functions Example 2 : Using array as input.
<?php
$trans = array("hi" => "all", "I said hello" => "hi from tutorialmines.in");
echo strtr("Hello hi, I said hello", $trans); 
?>

In above example, The two modes of behavior are substantially different. With three arguments, strtr() will replace bytes; with two, it may replace longer substrings. So, the output of above code in the browser is as below:

Hello all, hi from tutorialmines.in

strtr() – PHP Functions Example 3 :  behavior comparison.
<?php
echo strtr("baab", "ab", "01"),"\n";
$trans = array("ab" => "01");
echo strtr("baab", $trans);
?>

Output of above code in the browser is as below:

11001
ba01

You may also like...