2

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 any length, not just one character.

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

You have to be careful with array_splice. E.g. after insertion of the first two characters, index 7 does not point to G anymore, but to F. How would you solve this?
Yes, you have to have some iteration index and in every array_splice add this index to wanted position. Just control it by if..else based on max(insertion_index) where insertion_index is based on already made insertions. (just hope i haven't twisted in words :D)
0

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);

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.