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 关于#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测量血氧,找不到相关的代码。