Heim  >  Artikel  >  Backend-Entwicklung  >  PHP中str_replace函数用法细节

PHP中str_replace函数用法细节

WBOY
WBOYOriginal
2016-06-20 13:02:17897Durchsuche

​PHP中str_replace函数使用小结

在实际的程序开发中,执行字符串替换操作是一件非常经常的事,对str_replace函数的实用也会非常频繁。

这段时间在看《PHP和MySQL Web开发》一书看到str_replace讲解,一段小提示写到:可以为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
这个比较好理解,对两个字符串分别执行替换


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn