PHP str_replace() 函數的常見用法

來源:互聯網
上載者:User
<?php/*Function:    mixed str_replace ( mixed search, mixed replace, mixed subject [, int &count] )*/ //1==>// 輸出: <body text='black'>/*    這應該是最常見的用法了,從"<body text='%body%'>"中找到"%body%",然後替換成"black"*/$bodytag = str_replace("%body%", "black", "<body text='%body%'>"); //2==>// 輸出: Hll Wrld f PHP/*    參數 search 為數組的用法,逐個地遍曆數組來進行替換*/$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");$onlyconsonants = str_replace($vowels, "", "Hello World of PHP"); //3==>// 輸出: You should eat pizza, beer, and ice cream every day/*    參數 search 和 replace 均為數組的用法,且數組元素的個數相同,進行相互對應的替換*/$phrase  = "You should eat fruits, vegetables, and fiber every day.";$healthy = array("fruits", "vegetables", "fiber");$yummy = array("pizza", "beer", "ice cream");$newphrase = str_replace($healthy, $yummy, $phrase); //4==>// Use of the count parameter is available as of PHP 5.0.0/*    輸出匹配次數*/$str = str_replace("ll", "", "good golly miss molly!", $count);echo $count; // 2 //5==>// Order of replacement/*    自訂替換順序,防止重複替換*/$str       = "Line 1\nLine 2\rLine 3\r\nLine 4\n";$order    = array("\r\n", "\n", "\r");$replace = '<br />';// Processes \r\n's first so they aren't converted twice.$newstr = str_replace($order, $replace, $str); //6==>/*    這個是需要注意的,參數 search 和 replace 均為數組,第一次先替換 'a' ,結果為 'apple p',第二次接著替換 'p',因此會出現結果 'apearpearle pear'*/// Outputs: apearpearle pear$letters  = array('a', 'p');$fruit     = array('apple', 'pear');$text     = 'a p';$output  = str_replace($letters, $fruit, $text);echo $output;?>

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.