str_replace函数使用

函数原型:mixed str_replace(mixed needle,mixed new_needle,mixed haystack[,int &count]);
      needle:要被替换的字符串,new_needle:替换用的字符串,haystack:操作字符串,count:替换次数【可选参数】
     我们重点试验前三个在使用数组是的执行方式:
    
      在都不使用数组时,该函数直接使用new_needle替换所有的needle并返回替换后的字符串。如:str_replace("m","n","my name is jim!")返回ny nane is jin!

     1、只对needle使用数组。
     示例:str_replace(array(‘m’,’i’),’n’,"my name is jim!");返回:ny nane ns jnn!
     可以看出,函数顺序性的对数组中每个字符串进行替换,并返回替换后的字符串。
      2、只对new_needle使用数组。
     示例:str_replace(‘m’,array(‘n’,’z’),"my name is jim!\n")返回:Arrayy naArraye is jiArray!
      该替换比较有意思,如果只对第二个参数使用数组则函数将其作为字符串Array进行使用,将所有的needle替换为了数组。
     3、只对haystack使用数组。
     示例:str_replace("m","n",array("my name is jim!","the game is over!"))该语句执行结果返回一个数组,即分别为传入的两个字符串替换后的结果。
     如果输出数组内容会看到:ny nane is jin! the gane is over!

     4、对needle和new_needle都使用数组。
     示例:str_replace(array("m","i"),array("n","z"),"my name is jim!")返回:ny nane zs jzn!
      查看执行结果可以发现,如果前两个参数都使用数组则函数把数组各个对象项字符串进行了替换,及needle的第一项替换为new_needle的第一项。以此类推。
      如 果needle数组比new_deedle长,例 如:str_replace(array("m","i","s"),array("n","z"),"my name is jim!");返回:ny nane z jzn!可见,对于needle数组多出来的字符串被替换为了空串。
     如果new_needle数组比needle长,例 如:str_replace(array("m","i"),array("n","z","x"),"my name is jim!")返回ny nane zs jzn!可见new_needle多余的项被忽略。
     5、三个参数都使用数组。
     例如:str_replace(array("m","i"),array("n","z"),array("my name is jim!","the game is over"))返回的数组内容:ny nane zs jzn!the gane zs over
     这个比较好理解,对两个字符串分别执行替换。

发表评论

邮箱地址不会被公开。 必填项已用*标注

click to changeSecurity Code