1. 程式人生 > >字串反轉的幾種實現方式?陣列反轉

字串反轉的幾種實現方式?陣列反轉

1. strrev(); 只對英文友好

2.

function getRev($str,$encoding='utf-8'){

        $result = '';
        $len = mb_strlen($str);
        for($i=$len-1; $i>=0; $i--){
            $result .= mb_substr($str,$i,1,$encoding);
        }
        return $result;
    }
    $string = 'OK你是正確的Ole';
    echo getRev($string);

3.
$newArrOne = []; //初始化一個新的陣列   $newStrOne = '' ; //初始化一個新的字串   $newArrOne = str_split ( $str );   $arrCount = count ( $newArrOne );   for ( $i =0; $i < $arrCount ; $i ++) {   $newStrOne .= $newArrOne [ $i ];
  }   echo "<pre>" ;   print_r( $newStrOne );   echo "</pre>" ;   4. $newStrTwo = '' ; //初始化一個新的字串   $arrCountTwo = strlen ( $str );   for ( $i =1; $i <= $arrCountTwo
; $i ++) {   $newStrTwo .= substr ( $str , - $i , 1);   }   echo "<pre>" ;   print_r( $newStrTwo ). "\n" ;   echo "</pre>" ;   5. $newStrThree = '' ; //初始化一個新的字串 $arrCountThree = strlen ( $str ); for ( $i = $arrCountThree ; $i >=0; $i --) {   @ $newStrThree .= $str [ $i ]; } echo "<pre>" ; print_r( $newStrThree ). "\n" ; echo "</pre>" ; 

6.
$str = 'abcdefg'; $len = strlen($str); $times = $len/2; for($i = 0;$i <= $times; $i++ ){   $tmp = $str[$i];   $str[$i] = $str[$len-$i-1];   $str[$len-$i-1] = $tmp; } echo $str;   7. public   function  strrev ( $str ) {      $newstr = '' ;      $len = strlen ( $str );       for ( $i = $len ; $i >=0; $i --)      {          $newstr .= $str { $i };      }      return  $newst ;
}

8.
function reverse($str){  
    if ( $str  ==  '' ){           return  null;       }        if ( strlen ( $str ) == 1){            return  $str ;        } else {            $string  "" ;            for ( $i =1; $i <= strlen ( $str ); $i ++){                $string  .= substr ( $str ,- $i ,1);            }            return  $string ;        }   }  




array_reverse($arr) 函式 陣列反轉

strstr(),strchr(),strrchr(),stristr()