如何仅替换捕获的组?

时间:2016-02-17 21:23:37

标签: php regex

这是我的REGEX

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

我有一个这样的字符串:

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

现在我需要用另一次替换捕获的组。像这样:

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

或任何其他时间..!其实我的主要模式是:

{anything}{time }{AnyDigit}{AnyDigit}{:}{AnyDigit}{AnyDigit }{am|pm }{anything}
嗯,我怎么能这样做? (用捕获的组替换动态时间)

1 个答案:

答案 0 :(得分:4)

您需要将封闭的子模式封装到捕获组中,并使用反向引用来恢复新时间值之前和之后捕获的值:

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

替换为${1}10:10 pm$3${1}明确编号的第1组捕获文本的反向引用。这是必要的,因为下一个字符很可能是一个数字,如果$跟随2位数,PHP总是检查2位数的反向引用组。如果它看到$11,如果找不到它,则会弹出一个错误(与JavaScript不同)。

请参阅demo

这是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