2

I have a string, Chicago-Illinos1 and I want to add one to the end of it, so it would be Chicago-Illinos2.

Note: It could also be Chicago-Illinos10 and I want it to go to Chicago-Illinos11 so I can't rely on substr().

6
  • 7
    The first thing to consider when you hit a problem like this is should you be doing it in the first place. So, why do you want to do this (there's a good change there's a better/more-efficient/more-maintainable answer... Commented Jan 19, 2011 at 21:10
  • 2
    Also, you spelled Illinois incorrectly. Commented Jan 19, 2011 at 21:13
  • I have my reasons ircmaxell, it would take more then I am allowed in this comment box to explain. Commented Jan 19, 2011 at 21:13
  • 1
    @Steven I've updated your question to fix some typos and add a more obvious title. In future, I'd recommend spending a little bit more time explaining what you're attempting to achieve and at least checking for rudimentary spelling mistakes. This might seem harsh, but if you can't be bothered to spend time asking a question, why would you expect people to spend time answering it? Incidentally, there are some great hints over on tinyurl.com/so-hints Commented Jan 19, 2011 at 21:15
  • 1
    If your data is in a consistent format, i.e. City-StateN where N can be any integer number, you could easily parse it with regular expressions (something like ([^-]*)-([a-zA-Z]*)([0-9]*)) then build a new string with the incremented number. If your data is not consistent, you'll probably have to write a function that goes character-by-character and parses out the number, adds 1 to it, and creates a new string with the new number. I don't have time atm to help with something like that, but later I'll check back in and see if anyone's provided a better answer. Commented Jan 19, 2011 at 21:16

8 Answers 8

12

Complex solutions for a really simple problem...

$str = 'Chicago-Illinos1';
echo $str++; //Chicago-Illinos2

If the string ends with a number, it will increment the number (eg: 'abc123'++ = 'abc124').

If the string ends with a letter, the letter will be incremeted (eg: '123abc'++ = '123abd')

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

2 Comments

If the number is always present, it's overkill to bloat with regular expressions or other unnecessary functions. Incrementing/Decrementing Operators - rudimentary
Good to know, unfortunately in this case, it would mean turning 'Chicago-Illinos9' into 'Chicago-Illinot0'. So if we want wanting to go to more digits, he would have to start with 'Chicago-Illinos001' or something.
9

Try this

preg_match("/(.*?)(\d+)$/","Chicago-Illinos1",$matches);
$newstring = $matches[1].($matches[2]+1);

(can't try it now but it should work)

Comments

2
$string = 'Chicago-Illinois1';
preg_match('/^([^\d]+)([\d]*?)$/', $string, $match);
$string = $match[1];
$number = $match[2] + 1;

$string .= $number;

Tested, works.

Comments

1

explode could do the job aswell

<?php
$str="Chicago-Illinos1"; //our original string

$temp=explode("Chicago-Illinos",$str); //making an array of it
$str="Chicago-Illinos".($temp[1]+1); //the text and the number+1
?>

3 Comments

substr would probably be better in this case.
-1 That's only of use if the non-numeric text is known, which is pretty much the point of the question.
In the situation described the non-numeric text is known and even though substr is better i only mentioned the possibility.
0

I would use a regular expression to get the number at the end of a string (for Java it would be [0-9]+$), increase it (int number = Integer.parse(yourNumberAsString) + 1), and concatenate with Chicago-Illinos (the rest not matched by the regular expression used for finding the number).

Comments

0

You can use preg_match to accomplish this:

$name = 'Chicago-Illinos10';
preg_match('/(.*?)(\d+)$/', $name, $match);
$base = $match[1];
$num = $match[2]+1;
print $base.$num;

The following will output:

Chicago-Illinos11

However, if it's possible, I'd suggest placing another delimiting character between the text and number. For example, if you placed a pipe, you could simply do an explode and grab the second part of the array. It would be much simpler.

$name = 'Chicago-Illinos|1';
$parts = explode('|', $name);
print $parts[0].($parts[1]+1);

If string length is a concern (thus the misspelling of Illinois), you could switch to the state abbreviations. (i.e. Chicago-IL|1)

Comments

0
$str = 'Chicago-Illinos1';
echo ++$str;

http://php.net/manual/en/language.operators.increment.php

1 Comment

This answer incorrectly increments Chicago-Illinos9 to Chicago-Illinot0. As of PHP8.3, this answer emits a Deprecated notice. Deprecated: Increment on non-alphanumeric string is deprecated 3v4l.org/SNHYo
0

Without pre-isolating the numeric string suffix, there are two options to increment it.

  1. ++$string or $string++ - unary operators allow the incrementation and decrementation of values

  2. As of PHP8.3, str_increment() can be called with slightly more stable behavior, but the string itself must be entirely alphanumeric. Note that if you needed to increment an array of strings, having this new native function permits functional iterators (like array_map()) to call str_increment by its name alone.

Now for the bad news...

Both of these techniques will corrupt the left-neighboring character if the whole suffix number would ordinarily gain another digit. For instance, a9 would increment to b0 and z99 would become aa00.

If that wasn't enough to worry you, there is also the risk of incrementing a string value that resembles a float value. The string value 4567e4 would be incremented to the float-type value 45670001.0.

Read the manual: https://www.php.net/manual/en/language.operators.increment.php


Because those "convenient" techniques are rather unreliable, a better general-use approach would be to separate, increment, and replace the numeric suffix.

You can avoid declaring a temporary variable by calling preg_replace_callback(). I recommend this technique for directness and stability -- it will always return a string. Match the whole numeric suffix, increment it, then replace the original suffix with the incremented suffix. No side effects.

Code: (Demo)

$string = 'Chicago41Illinos9';

var_export(
    preg_replace_callback(
        '/\d+$/',
        fn($m) => ++$m[0],
        $string
    )
);
// Chicago41Illinos10

To edit a number anywhere in the string, just remove the $ (end of string anchor) from the pattern.

Comments

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.