本文實例講述了php實現子字符串位置相互對調互換的方法。分享給大家供大家參考,具體如下:
<?php/*子字符串位置互換 */$str1="Tom";$str2="Jack";$str="This is an example,you see Tom tell Jack something";function str_change($str,$str1,$str2){ $len1=strlen($str1); $len2=strlen($str2); $pos1=strpos($str,$str1); $str=substr_replace($str,$str2,$pos1,$len1);//替換$str1為$str2 $pos2= strpos($str,$str2,$len1+$pos1);//定位替換后字符串中原$str2字段的位置 return substr_replace($str,$str1,$pos2,$len2);//替換$str2為$str1}echo str_change($str,$str1,$str2);?>
運行結果為:
This is an example,you see Jack tell Tom something