dragon87836215 2019-06-22 05:08
浏览 110
已采纳

在preg_replace()中使用捕获组

I am having a hard time to understand the preg_replace().
This is what I have got so far. preg_replace($patter, $replacement, $string)
But, It confuses me when there is capturing groups in replacement. But still I get some of it. Like below

preg_replace('/(\w+)/', 'hello', 'say hello!')
I know it will result in 'hello hello!'. I can do something more with capturing group. preg_replace('/(\w+)/','\1 Hello', 'Say World!',1)

It will result in 'Say Hello World'.

This is what I don't get.

<?php
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);
?>
Output:
April1,2003

What ${1}1,$3 means?

What's the difference between using $1 \1 and <\1> What does this ${1}1 mean?

  • 写回答

1条回答 默认 最新

  • duanlan2003 2019-06-22 05:13
    关注

    Great question!

    For substitution parts

    My guess is that <\1> and $1 ${1} are pretty much the same, addressing capturing groups, except one of which has an extra <>.

    I think we are using ${1}1 since if we don't, we would have had $11, which does not simply exist, since we don't have that 11 capturing groups, we only have 3 of those, similar story for \11.

    ${1}1,$3 means the first capturing group, ${1}, and the number 1, and third capturing group, $3.

    Inside the Regular Expression

    When we use \1 or \2 inside a regular expression, not as a substitute, it would reference back the prior capturing groups $1 and $2, which is the same as \1 and 2 in the substitute section, which I also think that might create reasonable and valid confusions.

    Please see this demo for back-referencing.

    Reference

    Named Capturing Groups and Backreferences

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 写代码写代码单片机代码写代码写数字按键代码
  • ¥15 django按照距离进行排序
  • ¥15 (标签-微信|关键词-微信公众号)
  • ¥15 matlab中mjs用不了
  • ¥15 Ios抖音直播的时候如何添加自定义图片在直播间!
  • ¥60 riscv-pulpino总线上挂载axi从机
  • ¥15 ssh登录页面的问题
  • ¥50 关于在matlab上对曲柄摇杆机构上一点的运动学仿真
  • ¥15 jetson nano
  • ¥15 :app:debugCompileClasspath'.