I'm looking for a way to rotate a string to the left N times. Here are some examples:
Let the string be abcdef
1
time I want bcdefa
2
time I want cdefab
3
time I want defabc
$rotated = substr($str, $n) . substr($str, 0, $n);
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.
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
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;
}
?>
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
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;