开发者

PHP string manipulation, inside the string

开发者 https://www.devze.com 2023-02-02 17:29 出处:网络
I have string: ABCDEFGHIJK And I have two arrays of positions in that string that I want to insert different things to.

I have string:

ABCDEFGHIJK

And I have two arrays of positions in that string that I want to insert different things to.

Array
(
    [0] => 0
    [1] => 5
)

Array
(
    [0] => 7
    [1] => 9
)

Which if I decided to add the # character and the = character, it'd produce:

#ABCDE=FG#HI=JK

Is there any way I can do this without a complicated set of substr?

Also, # and = need to be variables that can be of an开发者_开发问答y length, not just one character.


You can use string as array

$str = "ABCDEFGH";
$characters = preg_split('//', $str, -1);

And afterwards you array_splice to insert '#' or '=' to position given by array
Return the array back to string is done by:

$str = implode("",$str);


This works for any number of characters (I am using "#a" and "=b" as the character sequences):

function array_insert($array,$pos,$val)
{
    $array2 = array_splice($array,$pos);
    $array[] = $val;
    $array = array_merge($array,$array2);

    return $array;
}
$s = "ABCDEFGHIJK";
$arr = str_split($s);
$arr_add1 = array(0=>0, 1=>5);
$arr_add2 = array(0=>7, 1=>9);
$char1 = '#a';
$char2 = '=b';
$arr = array_insert($arr, $arr_add1[0], $char1);
$arr = array_insert($arr, $arr_add1[1] + strlen($char1), $char2);
$arr = array_insert($arr, $arr_add2[0]+ strlen($char1)+ strlen($char2), $char1);
$arr = array_insert($arr, $arr_add2[1]+ strlen($char1)+ strlen($char2) + strlen($char1), $char2);
$s = implode("", $arr);
print_r($s);


There is an easy function for that: substr_replace. But for this to work, you would have to structure you array differently (which would be more structured anyway), e.g.:

$replacement = array(
    0 => '#', 
    5 => '=', 
    7 => '#', 
    9 => '='
);

Then sort the array by keys descending, using krsort:

krsort($replacement);

And then you just need to loop over the array:

$str = "ABCDEFGHIJK";

foreach($replacement as $position => $rep) {
    $str = substr_replace($str, $rep, $position, 0);
}

echo $str; // prints #ABCDE=FG#HI=JK

This works by inserting the replacements starting from the end of string. And it would work with any replacement string without having to determine the length of that string.

Working DEMO

0

精彩评论

暂无评论...
验证码 换一张
取 消