Search code examples
phpregexstringsplittext-parsing

Split string on last occurring underscore


I've got strings which consist of a label, underscores, and an ID:

  • "category_4"
  • "office_362"
  • "core_market_56"

What I'd like to have are two distinct chunks:

  • array("category", 4)
  • array("office", 362)
  • array("core_market", 56)

I know that I can isolate the numeric value, then turn around and subtract that from the original string, but I'm not sure if there's a cleaner way to do this in one step. Explode's limit argument seems close, and I have a feeling there's a regex pattern that could split by only the last underscore.


Solution

  • This is the regex you want

    (\w*)_(\d*)
    

    First matched group is your word, second - number. This is based, of course, on the assumption that number is always in the end and is separated from the word by underscore.