兩種php 字串替換函數

來源:互聯網
上載者:User

本文章主要講到兩種php 字串替換函數 str_replace與substr_replace前一種是替換所有haystace中的needle,並返回haystace替換後的結果,而substr_replace替換字串string中的一部分具體哪能一部分則取決於起始位置和選擇性參數length的值
最常用str_replace()
  
  函數原型:
  
  mixed str_replace(mixed needle,mixed new_needle,mixed haystace[,int &count])
  
  函數用new_needle替換所有haystace中的needle,並返回haystace替換後的結果.可選的第四個參數count,它包含要執行的替換操作次數.
  
  例:
  

 代碼如下 複製代碼
  <?php
  function n2n() {
   =array('1','2','3','4','5','6','7','8','9','0');
   =array("7","8","9","0","1","2","3","4","5","6");
   =strlen();
   for(=0;<;++){
    for(=0;<10;++)
  if(==){
   = str_replace(, , );
   break;
  }
   }
   return ;
  }
 
  ="1234abc56";
  echo n2n();
 
 ?>


  
  函數substr_replace()則用來在給定位置中尋找和替換字串中特定的子字串.原型:
  
  string substr_replace(string string,string replacement,int start,int[length]);

 代碼如下 複製代碼
 <?php
 echo substr_replace("hello world","earth",6);//hello earth
 ?>


 
 負數時
 

 代碼如下 複製代碼
 <?php
 substr_replace('huevos','x',-2,-2); //huevxos
 substr_replace('huevos','x',-2,-3); //huevxos
 substr_replace('huevos','x',-2,-3); //huevxos
 ?>


  
  函數使用字串replacement替換字串string中的一部分具體哪能一部分則取決於起始位置和選擇性參數length的值.
  
  start的值代表要替換字串位置的開始位移量.如果它為0或是一個正值,就是一個從字串開始處計算的位移量;如果它是一個負值,就是從字

聯繫我們

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