dongxikuo5171 2013-06-20 20:55
浏览 72
已采纳

php正则表达式加号

I'm playing around with PHP Regex in order to improve my skills with it.

I'm having a hard time trying to understand the plus sign - so I wrote the following code:

$subject = 'aaa bbb cccc dddd';
echo preg_replace('/(\w)/',"$1*",$subject) . '<br>';
echo preg_replace('/(\w+)/',"$1*",$subject) . '<br>';
echo preg_replace('/(\w)+/',"$1*",$subject) . '<br>';

With results in:

a*a*a* b*b*b* c*c*c*c* d*d*d*d*
aaa* bbb* cccc* dddd*
a* b* c* d*

I don't understand why these results come about. Can someone please explain what's going on in this example

  • 写回答

2条回答 默认 最新

  • dongyi9082 2013-06-20 21:10
    关注

    in regular expressions, + means one or more of the preceding character or group.

    The pattern /(\w)/, means match a single word character (a-zA-Z0-9_) in a single group. So it will match each letter. The first match group will be just a. The replace will replace each individual letter with that letter followed by an asterisk.

    The pattern /(\w+)/ will match one or more word characters in a group. So it will match each block of letters. The first match group will be aaa. The replace will replace each block of multiple letters followed by a asterisk.

    The last pattern /(\w)+/ is a little more tricky, but will match a single word character in a group but the + means that it will match one or more of the group. So the first match will be a, but the replace will replace all of the groups until there isn't a match with the last matched group (of course followed by an asterisk). So if you tried the string aaab ccc, your result would end up as b* c*. b is the last matched group in the first sequence and so the replace would use that.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥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系统搭建请教(跨境电商用途)