字符串反转的几种实现方式?数组反转

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()

猜你喜欢

转载自www.cnblogs.com/hanling/p/9955222.html