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

图片转代码服务由CSDN问答提供 功能建议

我正在尝试在某些位置(在本例中为字母“b”之前)将字符串插入字符串,但是 由于某种原因,我只在最后一个位置/出现时插入了文本(“test”)。

 &lt;?php 
 $ str =“aabaaaaabaaaaab”; 
 $ needle =“b”; 
 $ teststr =“test”; 
 $ lastPos =  0; 
 $ positions = array(); 
 
 
而(($ lastPos = strpos($ str,$ needle,$ lastPos))!== false){
 $ positions [] = $ lastPos;  
 $ lastPos = $ lastPos + strlen($ needle); 
} 
 
for($ i = 0; $ i&lt; count($ positions); $ i ++){
 $ newstring = substr_replace($ str,  $ teststr,$ positions [$ i],0); 
} 
 
echo $ newstring; 
?&gt;`
   
 
 

这会产生以下结果 输出:aabaaaaabaaaaa测试b 当需要的时候:aa测试aaaaa测试aaaaa测试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;
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douju2474 2018-01-14 16:05

    Would regular expressions work for you?

    <?php
    $str = "aabaaaaabaaaaab";
    echo preg_replace('~b~', ' test b', $str);
    
    评论
    解决 无用
    打赏 举报
  • duanou2526 2018-01-14 16:11
    $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

    评论
    解决 无用
    打赏 举报
  • doujia2386 2018-01-14 16:29

    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
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题