douweinu8562 2018-01-14 15:57
浏览 114
已采纳

PHP在某些位置将字符串添加到字符串-issue

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条回答 默认 最新

  • dongnaota6386 2018-01-14 16:17
    关注

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?