preg_split url slug和id

时间:2021-08-14 22:08:46

I currently have this URL pattern:

我目前有这个URL模式:

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!

任何帮助是极大的赞赏!谢谢!

1 个解决方案

#1


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 (?=...)

我使用 - 作为分隔符,我检查字符串末尾是否有一个数字,带有一个前瞻(?= ...)

#1


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 (?=...)

我使用 - 作为分隔符,我检查字符串末尾是否有一个数字,带有一个前瞻(?= ...)