dougao9864 2016-02-17 21:23
浏览 55
已采纳

如何仅替换捕获的组?

Here is my REGEX:

.*time\s+(\d{2}:\d{2}\s(am|pm)).*

I have a string like this:

there is some text and maybe some number or symbols time 12:32 am and there is some text
//                                                  ^^^^^
//                                                       ^^^^^^^^

Now I need to replace that captured group with another time. Like these:

there is some text and maybe some number or symbols time 01:21 am and there is some text

or any other time ..! Actually my main pattern is this:

{anything}{time }{AnyDigit}{AnyDigit}{:}{AnyDigit}{AnyDigit }{am|pm }{anything}

Well, How can I do that? (replace a dynamic time with captured group)

  • 写回答

1条回答 默认 最新

  • dongpao1083 2016-02-17 21:27
    关注

    You need to enclose the enclosing subpatterns into capturing groups and use backreferences to restore the captured values before and after a new time value:

    '~(.*time\s+)(\d{2}:\d{2}\s[ap]m)(.*)~'
      ^    1    ^^        2         ^^ 3^
    

    Replace with ${1}10:10 pm$3. The ${1} is an unambiguous numbered backreference to Group 1 captured text. It is necessary because the next character will most probably be a digit, and PHP always checks for the 2-digit backreference group if the $ is followed with 2 digits. If it sees $11, and if it does not find it, an error will pop up (unlike in JavaScript).

    See demo

    Here is an IDEONE demo:

    $re = '~(.*time\s+)(\d{2}:\d{2}\s[ap]m)(.*)~'; 
    $str = "there is some text and maybe some number or symbols time 12:32 am and there is some text"; 
    $new_time = "10:10 pm"; 
    $result = preg_replace($re, '${1}' . $new_time . '$3', $str);
    echo $result;
    // => there is some text and maybe some number or symbols time 10:10 pm and there is some text
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。