简体   繁体   中英

Increment a counter with regex in PHP

I am trying to increment a counter at the end of a string in 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. I want to get : 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.
  2. Lorem ipsum dolor sit amet (1337) : Lorem ipsum dolor sit amet is the main part and 1337 is the counter. I want to get : 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.

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 :

(?<=\()\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.

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.

Other approach

I had to use a non capturing group next to the name group because the negative lookahead isn't quantifiable apparently : exemple

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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