简体   繁体   English

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

[英]Using preg_replace in PHP - Strange Behaviour

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." 我的意图是“将所有出现的七位数替换为'NEWTRANSACTION:'以及那七位数。”

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. 我会使用/\\b\\d{7}\\b/ ,它的工作原理很像。 I'm new to regex, so I learned a bit here -- although not realizing the missing '0' was total boneheadedness on my part. 我是regex的新手,所以我在这里学到了一些东西-尽管没有意识到缺少的“ 0”对我来说完全是头疼。

My bad, showing 'NEWTRANSACTION: ' in the code, but showing 'NEWTRAN:' in the output. 我的错,在代码中显示'NEWTRANSACTION:',但在输出中显示'NEWTRAN:'。 I was just typing the output, instead of copy/paste, and shortened it accidentally. 我只是输入输出,而不是复制/粘贴,并意外缩短了输出。

Thanks again. 再次感谢。

Your code working fie after changing [1-9] to [0-9] (As your digits have 0 also at some places) [1-9]更改为[0-9]后,代码可以正常工作(因为在某些地方数字也为0)

<?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 https://eval.in/984686

Note:- A much shorter code given in a comment by @GrumpyCrouton,@kaii and @Barmar 注意:- @ GrumpyCrouton,@ kaii和@Barmar在注释中给出的代码要短得多

/\b\d{7}\b/

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM