首页 > 解决方案 > 将特定字符向右移动

问题描述

我需要将字符串中的特定字符从特定位置向右移动特定位置。字符串、位置和地点是输入,它可以是任何值。(使用 PHP 函数最多使用较少的行数)。

$string = 'Peacock';
$position = 2;
$places = 2;

move($string,$position,$places);

function move($string,$position,$places){

$string[($position-1)+$places] = $string[$position-1];
echo $string ; 
}

预期输出是 Paceock

标签: phpstring

解决方案


with forloop 将是一个很好的解决方案。

注意:$position必须从1.

<?php
$string = 'Peacock';
$position = 2;
$places = 2;

move($string,$position,$places);

function move($string,$position,$places){
    $keep =  $string[$position-1];
    for($i=0; $i<=$places;$i++){
        $string[($position-1)+$i] = $string[$position+$i];
    }
    $string[$position+$places-1] = $keep;
    echo $string ;
}

推荐阅读