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 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题