0

I currently have this URL pattern:

foo-bar-1
bar-foo-bar-2
etc

I'd like to get the words separated from the number but I'm having some trouble completely understanding how to do that.

I started with this which got me close:

$slug = 'foo-bar-1';
preg_split('/(\d+)$/', $slug);

array (size=2)
  0 => string 'foo-bar-' (length=8)
  1 => string '' (length=0)

But I can't seem to finish it up. I'd like it to be this:

array (size=2)
      0 => string 'foo-bar' (length=7)
      1 => string '1' (length=1)

Any help is greatly appreciated! Thank you!

Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124
travisneids
  • 593
  • 6
  • 7

1 Answers1

1

Try this:

preg_split('/-(?=\d+$)/', $slug);

I use - as separator and I check if it is followed by a number at the end of the string with a lookahead (?=...)

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125