PHP 截取字串函數 strtr/str_replace

來源:互聯網
上載者:User
/**

* 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

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.