I'm trying to insert text to string at certain positions (before letter "b" in this case), but for some reason the code I have only insert text (" test ")at the last position/occurance.
<?php
$str = "aabaaaaabaaaaab";
$needle = "b";
$teststr = " test ";
$lastPos = 0;
$positions = array();
while (($lastPos = strpos($str, $needle, $lastPos))!== false) {
$positions[] = $lastPos;
$lastPos = $lastPos + strlen($needle);
}
for ($i=0;$i<count($positions);$i++) {
$newstring = substr_replace($str,$teststr,$positions[$i],0);
}
echo $newstring;
?>`
this produces the following output: aabaaaaabaaaaa test b when the desired one whould be: aa test aaaaa test aaaaa test b