一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

两种php 字符串替换函数

时间:2010-11-10 编辑:简简单单 来源:一聚教程网

本文章主要讲到两种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,它包含要执行的替换操作次数.
  
  例:
  

 代码如下 复制代码
     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]);

 代码如下 复制代码
   echo substr_replace("hello world","earth",6);//hello earth
 ?>


 
 负数时
 

 代码如下 复制代码
   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或是一个正值,就是一个从字符串开始处计算的偏移量;如果它是一个负值,就是从字

热门栏目