/**
* 1. strtr 轉換指定字元
*
* string strtr ( string $str , string $from , string $to )
* string strtr ( string $str , array $replace_pairs )
*
* 該函數返回 str 的一個副本,並將在 from 中指定的字元轉換為 to 中相應的字元。
* 如果 from 與 to 長度不相等,那麼多餘的字元部分將被忽略。
*/
$str = 'http://flyer0126.iteye.com/';
echo strtr($str, 'IT', 'java');
//output: http://flyer0126.iteye.com/ strtr大小寫敏感
//如果 from 與 to 長度不相等,那麼多餘的字元部分將被忽略
echo strtr($str, 'it', 'java');
//output: haap://flyer0126.jaeye.com/
//iteye --> jaeye it只替換成了ja
//http --> haap 逐字元進行對應位置的替換,這樣不符合我們的初衷
echo strtr($str, 'it', '');
//output: http://flyer0126.iteye.com/ 沒有替換
echo strtr($str, 'it', ' ');
//output: http://flyer0126. teye.com/ 可以替換
/**
* 函數 strtr 的 from->to方式 總結一下:
* 1. 區分大小寫;
* 2. form與to長度不等時,多餘字元將被忽略,不可以少換多,也不可以多換少;
* 3. 逐字元進行對應位置替換;
* 4. 不可被替換為空白,可以替換為空白格。
*/
// 相比較而言,後一種方式顯而更合適
$replace_pairs = array(
'http://'=>'',
'it' => 'java'
);
echo strtr($str, $replace_pairs);
//output: flyer0126.javaeye.com/ 替換成功,符合替換初衷
/**
* 2. 函數 str_replace
* mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
*/
echo str_replace('it', 'java', $str);
//output: http://flyer0126.javaeye.com/
echo str_replace(array('http', ':', '//', '/'), '', $str);
//output: flyer0126.iteye.com
echo str_replace(array('http', 'it', '/'), array('https', 'java', ''), $str);
//output: https:flyer0126.javaeye.com