简体   繁体   English

在PHP中使用正则表达式增加计数器

[英]Increment a counter with regex in PHP

I am trying to increment a counter at the end of a string in PHP. 我试图在PHP的字符串末尾增加一个计数器。 The counter is always between parenthesis at the end of the string and the rest can be literally anything, meaning there could even be something that looks like the counter (ie : a number between parenthesis), but has a different meaning and shouldn't be altered. 计数器始终位于字符串末尾的括号之间,而其余部分实际上可以是任何值,这意味着甚至可能存在类似于计数器的内容(即:括号之间的数字),但含义不同,因此不应改变了。

Exemples : 范例:

  1. Foo (Bar) (666) (123) : Foo (Bar) (666) is the main part and 123 is the counter. Foo (Bar) (666) (123)Foo (Bar) (666)是主体,而123是计数器。 I want to get : Foo (Bar) (666) (124) . 我想要得到: Foo (Bar) (666) (124) (666) looks like the counter but since it isn't located at the end of the string it isn't considered as such. (666)看起来像是计数器,但是由于它不在字符串的末尾,因此不被认为是计数器。
  2. Lorem ipsum dolor sit amet (1337) : Lorem ipsum dolor sit amet is the main part and 1337 is the counter. Lorem ipsum dolor sit amet (1337)Lorem ipsum dolor sit amet是主要部分, 1337是柜台。 I want to get : Lorem ipsum dolor sit amet (1338) . 我想要得到: Lorem ipsum dolor sit amet (1338)

The exact implementation doesn't matter. 确切的实现无关紧要。 I just would like to use a regex to match the main part and the counter so I could put them in variables, increment the counter and build back the string. 我只是想使用一个正则表达式来匹配主体和计数器,所以我可以将它们放入变量中,增加计数器并重新构建字符串。

I can easily match the counter with something like \\((\\d*)\\)$ but I can't figure out how to match the rest of the string. 我可以轻松地将计数器与\\((\\d*)\\)$类的东西匹配,但是我不知道如何匹配其余的字符串。

What regex could do the job ? 什么正则表达式可以完成这项工作?

Well, I am not in love with this solution, but since you have asked for it: 好吧,我不喜欢这种解决方案,但是由于您已经提出了要求:

Here is a solution using preg_replace_callback : 这是使用preg_replace_callback的解决方案:

(?<=\()\d+(?=\)$)

Demo 演示版

Sample Code : 样例代码

$re = '/(?<=\()\d+(?=\)$)/';
$str = 'Lorem ipsum dolor sit amet (1337)';

$result = preg_replace_callback(
        $re,
        function ($matches) {
            return ++$matches[0];
        },
        $str
    );
echo "The result of the substitution is ".$result;

PS: If your "string" is actually the content of a multiline file replace $ with \\Z in $re to match the end of the file. PS:如果您的“字符串”实际上是多行文件的内容,请在$re中用\\Z替换$以匹配文件末尾。

At the same time as the accepted answer was posted, I found a way to do it the way I pictured it at first (ie : matching the name and the counter in separate groups). 在发布接受的答案的同时,我找到了一种方法,就像我最初想象的那样(即:在单独的组中匹配名称和计数器)。 So I figured I would post it as an answer, even though @wp78de's one is clearly better. 因此,我想我会将其发布为答案,即使@ wp78de的答案显然更好。

Other approach 其他方法

I had to use a non capturing group next to the name group because the negative lookahead isn't quantifiable apparently : exemple 我必须在name组旁边使用一个非捕获组,因为负前行显然无法量化: 例如

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

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