简体   繁体   中英

PHP Increase string value

I faced with some issue to increase the vale of the string, for example:

$string = "someString_1";

I need value somestring_2 . Ofcourse I can use something like this . But was trying to find another way and as a result I found that it will be enought make $string++ in my case;

$string++;
echo $string; //someString_2

It was great that I have only 1 string of code. BUT: Queston, is this correct way, or is there more better variants? (in condition that my string allways will have integer at the end)

And why it does not work when integer at the first position. For example if we make:

echo '1string' + '2string'; // result 3. This is how PHP work with string when we want make some mathemetic operations

you can try this regular expression. This snippet works and it gave me result as someString_2

 $string = "someString_1";
 function increment($matches) {
   return ++$matches[1];
 }

echo $string =  preg_replace_callback( "|(\d+)|", "increment", $string);

There is an explanation on php.net http://www.php.net/manual/en/language.operators.increment.php

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in PHP and Perl $a = 'Z'; $a++; turns $a into 'AA', while in C a = 'Z'; a++; turns a into '[' (ASCII value of 'Z' is 90, ASCII value of '[' is 91). Note that character variables can be incremented but not decremented and even so only plain ASCII alphabets and digits (az, AZ and 0-9) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.

Your solution probably works, but imagine, that someone has to modify your code some time later. Would you guess (without any research) what it does, if you saw $string++ somewhere? Even if it works, it's much better in my opinion, to create a function which does what you need, and has a name, which makes it clear, what it does.

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