douzhao6584 2011-12-23 08:55
浏览 100
已采纳

preg_replace的贪婪

echo preg_replace('/:*$/isD', ':', ':blue:');

A fairly simple PHP regex, which is designed to capture as many colons at the end of a string as possible (there may not be any at all) and replace it with just one. Or at least that's what I set out to do.

Here's the output:

:blue::

I expected, since preg_replace is greedy, that the colon at the end of the string would be captured, and thus I would get

:blue:

instead.

Oddly, using similar code to check for colons at the beginning of a string (i.e. /^(:)*/isD) works. I'm guessing this has something to do with the fact that regexes search from left to right, so in the non-working end of string example, it's finding only the end of the string, whereas in the working front of string example, it's already found the beginning of the string.

That said, what I can do to make preg_replace capture all of the ending colons?

  • 写回答

2条回答 默认 最新

  • dongpigui8898 2011-12-23 09:02
    关注
    echo preg_replace('/:+$/isD', ':', ':blue:');
    

    just replace the * (means zero or more) by a + (means one or more).

    The * matches at first all colons till the end and then the empty string, so there are two matches.

    Update

    To ensure exactly one colon at the end, you can use this:

    echo preg_replace('/^(.*?):*$/isD', '$1:', ':blue');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)