How can I replace only the last occurence of an number in a string with php?

Posted by Shawn on Stack Overflow See other posts from Stack Overflow or by Shawn
Published on 2012-09-20T15:36:40Z Indexed on 2012/09/20 15:37 UTC
Read the original article Hit count: 310

Filed under:
|

How would you change this:

a-10-b-19-c

into something like this:

a-10-b-20-c

using regular expressions in PHP?

The only solution I've found so far is:

  • reverse the original string -> "c-91-b-01-a"
  • find the first number -> "91"
  • reverse it -> "19"
  • turn in into a number (parseInt) -> 19
  • add 1 to it (+1) -> 20
  • turn it into a string again (toString) -> "20"
  • reverse it again -> "02"
  • replace the original match with this new number -> "c-02-b-01-a"
  • reverse the string -> "a-10-b-20-c"

I was hoping someone on SO would have a simpler way to do this... Anyone?

© Stack Overflow or respective owner

Related posts about php

Related posts about regex