dongtan5555 2012-10-11 15:44
浏览 8
已采纳

Preg match不会在第一场比赛时停止

I am trying to do a preg_replace so that i can format some text outputted from another program that doesnt look exactly how i want it to ....

here is a the snippet....

zzz:xxx1 _:somewhereElse_1 ;
xxx:yyy "dddd" ;
zzz:xxx2 _:somewhereElse_2 ;
yyy:zzz "ffff" ;   

_:somewhereElse_1
    I am somewhere else ;
 _:somewhereElse_2
    whatsup ;

What i am trying to do is make it look like this...

zzz:xxx1 I am somewhere else ;
xxx:yyy "dddd" ;
zzz:xxx2 whatsup ;
yyy:zzz "ffff" ;   

I have been trying to do it in various stages...

Stage 1. Extract the _:identifier from the top bit...

preg_match_all("/.*:.*_:somewhereElse_[(0-9)]+/", $data, $matches);

That works But what I cant do is extract the corresponding value from the bottom bit... none of my dam regular expressions work.

If you bear in mind that i have extracted all the somewhereElse_n the closest i can get is

preg_match_all("/(
$somewhereElse_n
.*;)?/s", $data, $matches);

The problem is the matches array as loads of empty places (nearly 2000) and its matching all the somewhereElse's instead of stopping after the first ..

      [1149] => 
      [1150] => 
      [1151] => 
      [1152] => 
         _:somewhereElse_1
            I am somewhere else ;
            So am i;
         _:somewhereElse_2
            whatsup ;
      [1153] => 
      [1154] => 

Any help would be gratefully accepted :D

  • 写回答

1条回答 默认 最新

  • dongyuchen9276 2012-10-11 15:52
    关注

    Your .* (any amount of anything) is "greedy", and tries to match as much as it possibly can while still being valid. As such, it's matching from the first match all the way to the last one.

    Changing it to .*? will make it non-greedy, which makes it match as little as possible while still remaining valid. As such, it should then match each individual occurrence as a separate match, instead of bundling them all into one.

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分