Rotate a string N times in PHP
I'm looking for a way to rotate a string to the left N times. Here are some examples:
Let the string be abcdef
- if I rotate it
1
time I wantbcdefa
- if I rotate it
2
time I wantcdefab
- if I rotate it
3
time I wantdefabc
- .
- .
- If I rotate 开发者_运维问答the string its string length times, I should get back the original string.
$rotated = substr($str, $n) . substr($str, 0, $n);
Here is one variant that allows arbitrary shifting to the left and right, regardless of the length of the input string:
function str_shift($str, $len) {
$len = $len % strlen($str);
return substr($str, $len) . substr($str, 0, $len);
}
echo str_shift('abcdef', -2); // efabcd
echo str_shift('abcdef', 2); // cdefab
echo str_shift('abcdef', 11); // fabcde
function rotate_string ($str, $n)
{
while ($n > 0)
{
$str = substr($str, 1) . substr($str, 0, 1);
$n--;
}
return $str;
}
There is no standard function for this but is easily implemented.
function rotate_left($s) {
return substr($s, 1) . $s[0];
}
function rotate_right($s) {
return substr($s, -1) . substr($s, 0, -1);
}
You could extend this to add an optional parameter for the number of characters to rotate.
function rotate_string($str) {
for ($i=1; $i<strlen($str)+1;$i++) {
@$string .= substr($str , strlen($str)-$i , 1);
}
return $string;
}
echo rotate_string("string"); //gnirts
Use this code
<?php
$str = "helloworld" ;
$res = string_function($str,3) ;
print_r ( $res) ;
function string_function ( $str , $count )
{
$arr = str_split ( $str );
for ( $i=0; $i<$count ; $i++ )
{
$element = array_pop ( $arr ) ;
array_unshift ( $arr, $element ) ;
}
$result=( implode ( "",$arr )) ;
return $result;
}
?>
You can also get N rotated strings like this.
$str = "Vijaysinh";
$arr1 = str_split($str);
$rotated = array();
$i=0;
foreach($arr1 as $a){
$t = $arr1[$i];
unset($arr1[$i]);
$rotated[] = $t.implode($arr1);
$arr1[$i] = $t;
$i++;
}
echo "<pre>";print_r($rotated);exit;
精彩评论