php實(shí)現(xiàn)子字符串位置相互對(duì)調(diào)互換的方法

字號(hào):


    本文實(shí)例講述了php實(shí)現(xiàn)子字符串位置相互對(duì)調(diào)互換的方法。分享給大家供大家參考,具體如下:
    <?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);
    ?>
    希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。