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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?