dtz8044 2018-04-05 12: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 12: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

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部