doumao1917 2013-04-26 15:15
浏览 40
已采纳

str replace - 替换x值

Assuming I have a string

$str="0000,1023,1024,1025,1024,1023,1027,1025,1024,1025,0000";

there are three 1024, I want to replace the third with JJJJ, like this :

output :

0000,1023,1024,1025,1024,1023,1027,1025,JJJJ,1025,0000

how to make str_replace can do it

thanks for the help

  • 写回答

7条回答 默认 最新

  • douyeke2695 2013-04-26 15:35
    关注

    Here is what I would do and it should work regardless of values in $str:

    function replace_str($str,$search,$replace,$num) {
        $pieces = explode(',',$str);
        $counter = 0;
        foreach($pieces as $key=>$val) {
            if($val == $search) {
                $counter++;
                if($counter == $num) {
                    $pieces[$key] = $replace;
                }
            }
        }
        return implode(',',$pieces);
    }
    
    $str="0000,1023,1024,1025,1024,1023,1027,1025,1024,1025,0000";
    
    echo replace_str($str, '1024', 'JJJJ', 3);
    

    I think this is what you are asking in your comment:

    function replace_element($str,$search,$replace,$num) {
        $num = $num - 1;
        $pieces = explode(',',$str);
        if($pieces[$num] == $search) {
            $pieces[$num] = $replace;
        }
        return implode(',',$pieces);
    }
    $str="0000,1023,1024,1025,1024,1023,1027,1025,1024,1025,0000";
    echo replace_element($str,'1024','JJJJ',9);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100