1/10/2014

difference between strtr and str_replace in php

strtr and str_replace may replace one string with other string or multiple strings.

But  they have little difference. You should take care of using them. Now I give some difference between them.

strtr usage

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

str_replace usage
mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

1. with two strings
$string = "1.10.0101";
echo strtr($string, '01', 'a'), '
'; // only replace 0 with a
echo str_replace('01', 'a', $string), '
'; //only replace 01 with a

output
1.1a.a1a1
1.10.aa

2. with array
$string = "1.10.0101";
echo strtr($string, array("1" => "10", "10" => "b")), '
'; //first replace 10 with b, then replace 1 with 10, but it will not replace the newly replaced value

echo str_replace(array("1", "10"), array("a", "b"), $string); // first replace 1 with a, then based on newly replaced string, replace 10 with b

output
10.b.0b10
a.a0.0a0a

3. str_replace can replace more string with one same string
$string = "1.10.0101"; 
echo strtr($string, array("1" => "x", "10" => "x")), '
';
echo str_replace(array("1", "10"), 'x', $string), '
';

output
x.x.0xx
x.x0.0x0x

No comments:

Post a Comment