0

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

4 Answers 4

1

You use $str as input for substring_replace, but you don't modify $str anywhere. Obviously only the last replacement will show. You can, for example, use $newstring as input for substring_replace, but then you positions are no longer correct. This can be avoided by making the replacements from right to left:

//snip

$newstring = $str;
for ($i = count($positions) - 1; $i >= 0; $i--) {
  $newstring = substr_replace($newstring, $teststr, $positions[$i], 0);
}

echo $newstring;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! I have been banging my head against the wall with this issue for hours now!
0

Would regular expressions work for you?

<?php
$str = "aabaaaaabaaaaab";
echo preg_replace('~b~', ' test b', $str);

1 Comment

It probably would, but I try to avoid regex at all cost. Thanks for your input though.
0
$str = "aabaaaaabaaaaab";
$needle = "b";
$teststr = " test ";
$lastPos = 0;
$positions = explode($needle, $str);
foreach($positions as $k=>$v) {
    $positions[$k]=$v.$teststr.$needle;
}
$positions=implode($positions);
echo $positions;

Try This

1 Comment

Thanks mate, I tried this code also, but I found that it adds a additional "test b" in the end. Ie. the result is: aa test baaaaa test baaaaa test b test b.
0

Following should work

$str = "aabaaaaabaaaaab";
$needle = "b";
$teststr = " test ";

for ($i=0;$i<strlen($str);$i++) {
    if($str[$i]==$needle ){
        echo $teststr.$str[$i]; 
    }else{
        echo $str[$i];
    }
}

echo $newstring;

**Output** 
aa test baaaaa test baaaaa test b

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.