strtr
strtr
Translate characters or replace substrings
string **strtr** string $string string $from string $to
Alternative signature (not supported with named arguments):
string **strtr** string $string array $replace_pairs
If given three arguments, this function returns a copy of
where all occurrences of each (single-byte)
character in have been translated to the
corresponding character in , i.e., every
occurrence of has been replaced with
, where is a valid
offset in both arguments.
string``from``to``$from[$n]``$to[$n]``$n
If and have
different lengths, the extra characters in the longer of the two
are ignored. The length of will be the same as
the return value's.
from``to``string
If given two arguments, the second should be an in the
form . The return value is
a where all the occurrences of the array keys have been
replaced by the corresponding values. The longest keys will be tried first.
Once a substring has been replaced, its new value will not be searched
again.
array``array('from' => 'to', ...)``string
In this case, the keys and the values may have any length, provided that
there is no empty key; additionally, the length of the return value may
differ from that of .
However, this function will be the most efficient when all the keys have the
same size.
string
string
The being translated.
string
from
The being translated to .
string``to
to
The replacing .
string``from
replace_pairs
The parameter may be used instead of
and , in which case it's an
in the form .
replace_pairs``to``from``array``array('from' => 'to', ...)
If contains a key which is an empty
(), the element is ignored;
as of PHP 8.0.0 is raised in this case.
`replace_pairs``string``""``E_WARNING`
Returns the translated .
string
Voorbeeld: example
<?php
$addr = "The river å";
// In this form, strtr() does byte-by-byte translation
// Therefore, we are assuming a single-byte encoding here:
$addr = strtr($addr, "äåö", "aao");
echo $addr, PHP_EOL;
?>
The next example shows the behavior of when
called with only two arguments. Note the preference of the replacements
( is not picked because there are longer matches)
and how replaced text was not searched again.
strtr``"h"
Voorbeeld: example with two arguments
<?php
$trans = array("h" => "-", "hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
?>
hello all, I said hi
The two modes of behavior are substantially different. With three arguments,
will replace bytes; with two, it may replace
longer substrings.
strtr
Voorbeeld: behavior comparison
<?php
echo strtr("baab", "ab", "01"),"\n";
$trans = array("ab" => "01");
echo strtr("baab", $trans);
?>
1001
ba01
str_replace``preg_replace