dongpeiwei8589 2013-10-06 14:16
浏览 32
已采纳

在没有正则表达式的给定位置后替换字符串中的所有匹

I have a string abcxdefxghix. I wish to remove all "x"s except the first one. I can easily find the position of the first "x" using strpos(), so wish to remove all "x"s after that position. str_replace() performs a replacement of a given string with another, but doesn't allow a start position. substr_replace() gives a start position, but doesn't have the search parameter. I realize this can be done using preg_replace() but it seems like it should also be possible with without regular expressions (or without some crazy split/replace/assemble strategy).

  • 写回答

3条回答 默认 最新

  • douyou8266 2013-10-06 14:31
    关注

    I 'd most likely do it the old-fashioned way:

    $index = strpos($input, $needle);
    if ($index !== false) {
        $input = substr($input, 0, $index + 1).
                 str_replace($needle, $replacement, substr($input, $index + 1));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 C++ 句柄后台鼠标拖动如何实现
  • ¥15 有人会SIRIUS 5.8.0这个软件吗
  • ¥30 comsol仿真等离激元
  • ¥15 静电纺丝煅烧后如何得到柔性纤维
  • ¥15 (标签-react native|关键词-镜像源)
  • ¥100 照片生成3D人脸视频
  • ¥15 伪装视频时长问题修改MP4的时长问题,
  • ¥15 JETSON NANO
  • ¥15 VS开发qt时如何在paintgl函数中用pushbutton控制切换纹理
  • ¥20 关于 openpyxl 处理excel文件地问题