dtz8044 2018-04-05 20:38
浏览 49
已采纳

在PHP中使用preg_replace - 奇怪的行为

I have the following:

$string = '4745518 some text 4510018 some text 4743618 4745518 some text 4510518 some text';
$newstring = preg_replace('/[1-9]{7,7}/','NEWTRANSACTION: $0',$string);

My intent is "replace all occurrences of seven digits with 'NEWTRANSACTION: ' plus those seven digits."

However, my result is:

 NEWTRANS: 4745518 some text 4510018 some text NEWTRANS: 4743618 NEWTRANS: 4745518
 some text 4510518 some text

In other words, it appears that only some of the seven-digit groups are being replaced. If I edit the original string, shift the seven digit groups around, those same seven digit groups get replaced. It's like only certain combinations of numbers are being marked for replacement. My actual input string is hundreds of lines long, and it really appears that random seven-digit groups are being replaced.

Can anyone see what's wrong? Thanks in advance.

=== EDIT === Thanks for all of the help so quickly. I would up using /\b\d{7}\b/ and it works like a charm. I'm new to regex, so I learned a bit here -- although not realizing the missing '0' was total boneheadedness on my part.

My bad, showing 'NEWTRANSACTION: ' in the code, but showing 'NEWTRAN:' in the output. I was just typing the output, instead of copy/paste, and shortened it accidentally.

Thanks again.

  • 写回答

1条回答 默认 最新

  • donglaoping9702 2018-04-05 20:44
    关注

    Your code working fie after changing [1-9] to [0-9] (As your digits have 0 also at some places)

    <?php
    
    $string = '4745518 some text 4510018 some text 4743618 4745518 some text 4510518 some text';
    echo $newstring = preg_replace('/[0-9]{7,7}/','NEWTRANSACTION: $0',$string);
    

    https://eval.in/984686

    Note:- A much shorter code given in a comment by @GrumpyCrouton,@kaii and @Barmar

    /\b\d{7}\b/
    

    Output:-https://eval.in/984792

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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看