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
1/10/2014
1/09/2014
Generating Random Passwords Class with PHP
You may create one random string or strong random password by using the following php class at will.
/**
* Description of RandomString
*
* @package
*/
class RandomString
{
/**
*
* @param int $length
* @return string
*/
static public function getRandom($length)
{
$randomData = base64_encode(file_get_contents('/dev/urandom', false, null, 0, $length) . uniqid(mt_rand(), true));
return substr(strtr($randomData, array('/' => '', '=' => '', '+' => '')), 0, $length);
}
}
/**
* Description of RandomString
*
* @package
*/
class RandomString
{
/**
*
* @param int $length
* @return string
*/
static public function getRandom($length)
{
$randomData = base64_encode(file_get_contents('/dev/urandom', false, null, 0, $length) . uniqid(mt_rand(), true));
return substr(strtr($randomData, array('/' => '', '=' => '', '+' => '')), 0, $length);
}
}
Subscribe to:
Posts (Atom)