phpstringreplacestrsplitprepend

Prepend string before each character of another string


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?


Solution

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