dss89001 2012-08-02 20:24
浏览 82
已采纳

preg_replace匹配所有但第一次出现的东西?

I'm looking for a way to replace all but first occurrences of a group or some character.

For example a following random string:

+Z1A124B555ND124AB+A555

1,5,2,4,A,B and + are repeating through out the string.

124, 555 are groups of characters that are also reoccurring.

Now, let's say I want to remove every but first occurrence of 555, A and B.

What regex would be appropriate? I could think of an example replacing all:

preg_replace('/555|A|B/','',$string);

Something like ^ that, but I want to keep the first occurrence... Any ideas?

  • 写回答

3条回答 默认 最新

  • dtah63820 2012-08-02 20:35
    关注

    Are your strings always delimited by plus signs? Do 555, A, and B always occur in the first "group" (delimited by +)?

    If so, you can split, replace and then join:

    $input = '+Z1A124B555+A124AB+A555';
    $array = explode('+', $input, 3); // max 3 elements
    $array[2] = str_replace(array('555', 'A', 'B'), '', $array[2]);
    $output = implode('+', $array);
    

    ps. No need to use regexes, when we can use a simple str_replace


    Use the preg_replace_callback function:

    $replaced = array('555' => 0, 'A' => 0, 'B' => 0);
    $input = '+Z1A124B555+A124AB+A555';
    $output = preg_replace_callback('/555|[AB]/', function($matches) {
      static $replaced = 0;
      if($replaced++ == 0) return $matches[0];
      return '';
    }, $input);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图