0

First of all: I'm very bad with regular expressions, the ones I already have here I found on the net.

I want to increment the first number in a string, e.g. $teststring = "abcd1234efgh56";

I have already found the following:

preg_replace( "|(\d+)|e", "$1+1", $teststring);

will result in abcd1235efgh57

preg_replace( "|(\d+)(?!.*\d)|e", "$1+1", $teststring);

will result in abcd1234efgh57

but how do I increment ONLY the first number (1234 in the example) while leaving the rest of the string as is?

Thank you very much in advance

4 Answers 4

3

check out the docs: php.net manual on preg_replace

use the fourth parameter to limit the number of replaces

Sign up to request clarification or add additional context in comments.

Comments

0

You could use:

preg_replace('/([^0-9]*)(\d+)(.*)/e', '"$1" . ($2+2) . "$3"' , $str, 1);

This would match all non-numeric characters (if any) before the first number as $1, the first number as $2, and all following characters (if any) as $3.

It then outputs the string with 2 added to the first number (you can change $2+2 to $2+NUMBER).

The final parameter 1 in the function is limiting the repeats to 1 time only...

Comments

0

The optional fourth parameter of preg_replace is limit :

preg_replace($search , $replace, $subject, $limit)

You can put 1 for your case..

it will give you

$teststring = 'abcd1235efgh56'

Comments

-1

Try

preg_replace('/^([^0-9]+)?([0-9]+)([^0-9]+)?/', "$2+1", $teststring);

4 Comments

This will only work if there are exactly two numbers in the string.
Just tested it and it works with 1 or more numbers in the string
Ahh, never mind. I was confused by the unnecessary [^0-9]+.
I just tried it, the output was 1234+156. That's not even close to right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.