PHP strtr() Function
strtr() function translate characters or replace substrings within a string.
The following table summarizes the technical details of this function.
|Return Value:||Returns the translated string. If the array parameter contains a key which is an empty string (""),
The basic syntax of the
strtr() function is given with:
The following example shows the
strtr() function in action.
<?php // Sample string $str = "Mary had a little lamb"; // Performing replacement echo strtr($str, "My", "Sa"); ?>
If from and to have different lengths, the extra characters in the longer of the two are ignored, which means the length of the resulting string will remain the same.
You can alternatively use an array instead of from and to parameters. In this case, the keys and the values may have any length, provided that there is no empty key; additionally, the length of the resulting string may differ from the original string. Here's an example:
<?php // Sample string $str = "hi all, I said hello"; // Defining replacement pairs $replace_array = array("h" => "x", "hi" => "hello", "hello" => "hi"); // Performing replacement echo strtr($str, $replace_array); ?>
If you see the output of the above example you will notice "h" is not picked by this function because there are longer matches available. Also, the replaced text was not searched again.
strtr() function accepts the following parameters.
|string||Required. Specifies the string to translate.|
|from||Required. Specifies the characters or substring to be replaced.|
|to||Required. Specifies the replacement substring.|
|array||Required (unless from and to is used). Specifies an array in the form
Here're some more examples showing how
strtr() function actually works:
This function behaves differently in two and three arguments modes. With three arguments,
strtr() will replace characters; whereas with two, it may replace longer substrings.
<?php // Sample string $str = "woow"; // Defining replacement pairs $replace_array = array("wo" => "x1"); // Performing replacement echo strtr($str, "wo", "x1")."<br>"; echo strtr($str, $replace_array); ?>