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 want
bcdefa
if I rotate it 2 time I want
cdefab
if I rotate it 3 time I want
defabc
.
.
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;
Related
I am trying to capitalize the first letter of word in php without using ucfirst() function But i am not able do it , but i am struggling with this. Please tell me its answer.
<?php
$str ="the resources of earth make life possible on it";
$str[0] = chr(ord($str[0])-32);
$length = strlen($str);
for($pos=0; $pos<$length; $pos++){
if($str[$pos]==' '){
$str[$pos+1] = chr(ord($str[$pos+1])-32);
}
}
echo $str;
?>
Without using the function ucfirst, you can do it like this:
$firstLetter = substr($word, 0, 1);
$restOfWord = substr($word, 1);
$firstLetter = strtoupper($firstLetter);
$restOfWord = strtolower($restOfWord);
print "{$firstLetter}{$restOfWord}\n";
To do it for each word, use explode(' ', $string) to get an array of words, or preg_split('#\\s+#', $string, -1, PREG_SPLIT_NO_EMPTY) for better results.
I would advise against just subtracting 32 from the first character of the next word:
you do not know it is a letter
you do not know it isn't already capitalized
you do not know it exists
you do not know it is not another space
At the very least check that its ord() value lies between ord('A') and ord('Z').
To do this all without case-changing functions, you'd do
$text = implode(' ',
array_map(
function($word) {
$firstLetter = substr($word, 0, 1);
if ($firstLetter >= 'a' && $firstLetter <= 'z') {
$firstLetter = chr(ord($firstLetter)-32);
}
$restOfWord = substr($word, 1);
$len = strlen($restOfWord);
for ($i = 0; $i < $len; $i++) {
if ($restOfWord[$i] >= 'A' && $restOfWord[$i] <= 'Z') {
$restOfWord[$i] = chr(ord(restOfWord[$i])+32);
}
}
return $firstLetter . $restOfWord;
},
preg_split('#\\s+#', $originalText, -1, PREG_SPLIT_NO_EMPTY)
)
);
as such...
$str ="the resources of earth make life possible on it";
$words=array_map(static fn($a) => ucfirst($a), explode(' ', $str));
echo implode(' ', $words);
with ord and chr
$ordb=ord('b'); //98
$capitalB=chr(98-32); //B
$ordA=ord('a'); //97
$caiptalA=chr(97-32); //A
//so
function capitalize(string $word)
{
$newWord = '';
$previousCharIsEmpty = true;
$length = strlen($word);
for ($a = 0; $a < $length; $a++) {
if ($word[$a] === ' ') {
$newWord .= ' ';
$previousCharIsEmpty = true;
} else {
if ($previousCharIsEmpty === true) {
$ord = ord($word[$a]);
$char = chr($ord - 32);
$newWord .= $char;
$previousCharIsEmpty = false;
} else {
$newWord .= $word[$a];
}
$previousCharIsEmpty = false;
}
return $newWord;
}
$word = 'this for example by dilo abininyeri';
echo capitalize($word);
and output
This For Example By Dilo Abininyeri
We cannot do this without any function. We have to use some function. Like you have applied the for-loop and for strlen function.
<?php
$str ="the resources of earth make life possible on it";
$str[0] = chr(ord($str[0])-32);
$length = strlen($str);
for($pos=0; $pos<$length; $pos++){
if($str[$pos]==' '){
$str[$pos+1] = chr(ord($str[$pos+1])-32);
}
}
echo $str;
?>
I have a string like $str.
$str = "00016cam 321254300022cam 321254312315300020cam 32125433153";
I want to split it in array like this. The numbers before 'cam' is the string length.
$splitArray = ["00016cam 3212543", "00022cam 3212543123153", "00020cam 32125433153"]
I have tried following code:
$lengtharray = array();
while ($str != null)
{
$sublength = substr($str, $star, $end);
$star += (int)$sublength; // echo $star."<br>"; // echo $sublength."<br>";
if($star == $total)
{
exit;
}
else
{
}
array_push($lengtharray, $star); // echo
print_r($lengtharray);
}
You can try this 1 line solution
$str = explode('**', preg_replace('/\**cam/', 'cam', $str)) ;
If your string doesn't contain stars then I'm afraid you need to write a simple parser that will:
take characters from the left until it's not numeric
do substr having the length
repeat previous steps on not consumed string
<?php
$input = "00016cam 321254300022cam 321254312315300020cam 32125433153";
function parseArray(string $input)
{
$result = [];
while ($parsed = parseItem($input)) {
$input = $parsed['rest'];
$result[] = $parsed['item'];
}
return $result;
}
function parseItem(string $input)
{
$sLen = strlen($input);
$len = '';
$pos = 0;
while ($pos < $sLen && is_numeric($input[$pos])) {
$len .= $input[$pos];
$pos++;
}
if ((int) $len == 0) {
return null;
}
return [
'rest' => substr($input, $len),
'item' => substr($input, 0, $len)
];
}
var_dump(parseArray($input));
this code works for me. hope helps.
$str = "**00016**cam 3212543**00022**cam 3212543123153**00020**cam 32125433153";
$arr = explode("**", $str);
for ($i=1; $i < sizeof($arr); $i=$i+2)
$arr_final[]=$arr[$i].$arr[$i+1];
I am trying to split a string into 1, 2 and 3 segments.
For example, i currently have this:
$str = 'test';
$arr1 = str_split($str);
foreach($arr1 as $ar1) {
echo strtolower($ar1).' ';
}
Which works well on 1 character splitting, I get:
t e s t
However when I try:
$arr2 = str_split($str, 2);
I get:
te st
Is there a way so that I can output this? :
te es st
and then also with 3 characters like this?
tes est
Here it is:
function SplitStringInWeirdWay($string, $num) {
for ($i = 0; $i < strlen($string)-$num+1; $i++) {
$result[] = substr($string, $i, $num);
}
return $result;
}
$string = "aeioubcdfghjkl";
$array = SplitStringInWeirdWay($string, 4);
echo "<pre>";
print_r($array);
echo "</pre>";
PHPFiddle Link: http://phpfiddle.org/main/code/1bvp-pyk9
And after that, you can just simply echo it in one line, like:
echo implode($array, ' ');
Try this, change $length to 1 or 3:
$string = 'test';
$length = 2;
$start = -1;
while( $start++ + $length < strlen( $string ) ) {
$array[] = substr( $string, $start, $length );
}
print_r( $array );
/*
Array
(
[0] => te
[1] => es
[2] => st
)
*/
Use
$string{0} $string{1} $string{n}
to get the characters you want !
Then you can use a loop on your string using strlen
$length = strlen($string);
for($i = 0; $i < $length; ++$i){
// Your job
}
Then use $i, $i - 1, $i + 1 to pick the characters.
<?php
function my_split($string, $count){
if(strlen($string) <= $count){
return $string;
}
$my_string = "";
for($i; $i< strlen($string) - $count + 1; $i++){
$my_string .= substr($string, $i, $count). ' ';
}
return trim($my_string);
}
echo my_split('test', 3);
?>
And will have "tes est"
Simplest way, you can do it with chunk_split:
$str = "testgapstring";
$res = chunk_split($str, 3, ' ');
echo $res; // 'tes tga pst rin g '
but you have extra space symbol at the end, also if you need this to be an array something will work:
$chunked = chunk_split($str, 3, ' ');
$arr = explode(' ', rtrim($chunked));
Other example:
echo $chunked = rtrim(chunk_split('test', 2, ' ')); // 'te st'
function luhn_Approved($;500) {
$str = '';4815821101619134=2408101
foreach( array_reverse( str_split( $num ) ) as $i => $c ) $str .= ($i % 2 ? $c * 2 : $c );
return array_sum( str_split($str) ) % 10 == 0;
}
function SplitStringInWeirdWay($string, $0) {
for ($i = 0; $i < strlen($string)-$num+1; $i++) {
$result[] = substr($string, $i, $num);
}
return $result;
}
$string = "aeioubcdfghjkl";
$array = SplitStringInWeirdWay($string, 4);
echo "<pre>"; print_r($array); echo "</pre>";
Hey i have a php program which is to spilt the words. I wanted it not to come in array. Instead of array i wanted it in div or span. Please help me to solve these problem. Thanks in advance.
Here is my php code
<?php
function str_split_len($str, $len)
{
if( $len > strlen($str) )
{
return false;
}
$strlen = strlen($str);
$result = array();
$words = ($strlen / $len);
for( $x = 1; $x <= $len; $x++ )
{
$result[] = substr($str, 0, $words);
$str = substr($str, $words, $strlen);
}
return $result;
}
/* Example */
$res = str_split_len("Split me !haha!", 3);
print_r($res);
?>
you can use implode function to join array:
$res = str_split_len("Split me !haha!", 3);
echo '<span>'.implode('</span><span>', $res).'</span>';
Just use a string instead of an array and concatenate the parts with <div> or <span>:
<?php
function str_split_len($str, $len)
{
if( $len > strlen($str) )
{
return false;
}
$strlen = strlen($str);
$result = '';
$words = ($strlen / $len);
for( $x = 1; $x <= $len; $x++ )
{
$result .= '<div>'.substr($str, 0, $words).'</div>';
$str = substr($str, $words, $strlen);
}
return $result;
}
/* Example */
$res = str_split_len("Split me !haha!", 3);
echo $res;
?>
And you will get
<div>Split</div><div> me !</div><div>haha!</div>
I have a PHP problem where I have a string of numbers:
ie/ 1,2,3,4,5,6,7,8,9...... X
I know the first number and have to create a string X long so that it wraps around
for example if my string is 1,2,3,4,5 and my first number is 4 - i need to return the string:
4,5,1,2,3
I'd like to create a function to achieve this - any help would be great!
Thanks.
<?php
function MyWrap($string, $first)
{
$splitHere = strpos($string, $first);
return rtrim(substr($string, $splitHere).','.substr($string, 0, $splitHere), ',');
}
echo MyWrap('1,2,3,4,5', '4');
?>
Output:
4,5,1,2,3
$pos = strpos($string,$first_number);
return substr($s,$pos).','.substr($s,0,$pos);
I believe I understand what you need - try this:
function numsWrap($firstNumber, $total) {
$newStr = "";
$inc = $firstNumber;
for($i = 0; $i < $total+1; $i++) {
if($i == 0) {
$newStr .= $inc;
} else {
if($inc == $total) {
$newStr .= "," . $inc;
$inc = 0;
} else {
$newStr .= "," . $inc;
}
}
$inc++;
}
return $newStr;
}
Usage:
echo numsWrap(5, 10);
5,6,7,8,9,10,1,2,3,4,5
function wrapAroundNeedle($myString, $myNeedle)
{
$index = strrpos($myString, $myNeedle);
return substr($myString, $index).",".substr($myString, 0, $index - 1);
}
How to roll your own. Note that strrpos only allows single characters for $needle in php 4.
string substr ( string $string , int $start [, int $length ] )
int strrpos ( string $haystack , string $needle [, int $offset = 0 ] )
http://php.net/manual/en/function.substr.php
http://php.net/manual/en/function.strrpos.php