Prepend string before each character of another string

63 Views Asked by At

I have the following code:

$target = "abcwa";

for($w = 0; $w <=strlen($target)-1; $w++)
{
  $str = str_split($target[$w],1); //a
  $str_ = $str[$w];
            
  echo "w:";$w;
  echo $str_;
}// end for w

It is printing:

w:a
Warning: Undefined array key 1 in /in/n705C on line 8
w:
Warning: Undefined array key 2 in /in/n705C on line 8
w:
Warning: Undefined array key 3 in /in/n705C on line 8
w:
Warning: Undefined array key 4 in /in/n705C on line 8
w:

Line 8 is $str_ = $str[$w];.

However the goal is to print: w:aw:bw:cw:ww:a

What is wrong?

2

There are 2 best solutions below

0
mickmackusa On BEST ANSWER

I would abandon your original code because it is verbose and has multiple failing components.

Instead, just use regex to insert your desired string before each character.

Codes: (Demo)

echo preg_replace('/./', 'w:$0', $target);

Or

echo preg_replace('/(?=.)/', 'w:', $target);
0
Alex Howansky On

Your loop has:

$w <= strlen($target) - 1

This is more commonly done with:

$w < strlen($target)

But you don't need any loops at all here. Start by splitting the string into an array of individual letters:

str_split($target);

This gives you: ['a', 'b', 'c', 'w', 'a']

Then re-combine that array into a string, but with "w:" between each element:

echo implode('w:', str_split($target));

This gives you:

aw:bw:cw:ww:a

Then just tack on your leading "w:":

echo 'w:' . implode('w:', str_split($target));

Which yields:

w:aw:bw:cw:ww:a

Alternatively, you could add a space to the start of your string, so that the split has one extra character at the start, for the implode to act on:

echo implode('w:', str_split(' ' . $target));

Which yields:

 w:aw:bw:cw:ww:a

(Note there's an extra space in the output in this case, if that matters.)