php - Move specific character to right
Get the solution ↓↓↓I need to move a specific character in a string from a specific position to right by specific places. string, position, and places are inputs it can be any value. (Maximum use less number of lines using PHP functions).
$string = 'Peacock';
$position = 2;
$places = 2;
move($string,$position,$places);
function move($string,$position,$places){
$string[($position-1)+$places] = $string[$position-1];
echo $string ;
}
Expected output is Paceock
Answer
Solution:
with{-code-1}
loop will be a good solution.
NB: the$position
must be start from1
.
<?php
$string = 'Peacock';
$position = 2;
$places = 2;
move($string,$position,$places);
function move($string,$position,$places){
$keep = $string[$position-1];
{-code-1}($i=0; $i<=$places;$i++){
$string[($position-1)+$i] = $string[$position+$i];
}
$string[$position+$places-1] = $keep;
echo $string ;
}
Answer
Solution:
If you do not mind you can modify the string as well.
$string = 'Peacock';
$position = 2;
$places = 2;
function move($string,$position,$places){
$char = $string[$position-1];
$string = substr_replace($string, '', $position-1, 1);
$string = substr_replace($string, $char, $position+$places-1, 0);
echo $string;
}
move($string,$position,$places);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: warning: undefined array key
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.