user2572639
user2572639

Reputation: 55

How can I get an ID from the end of a string in PHP?

I am trying to extract an ID from the URL using this code:

   preg_match_all('!\d+!', $slug, $matches);

However, if the url/slug is domain.com/number-5-shirt-28723 it thinks that the ID is 5 rather than 28723

It works fine if there are no numbers at all.

How can I make sure the ID is from the very end of the string after the last - ?

Upvotes: 1

Views: 162

Answers (1)

yergo
yergo

Reputation: 4970

$ makes you sure you reached the end of string, so you may try to modify your preg to:

preg_match_all('/\d+$/', $slug, $matches);

Upvotes: 4

Related Questions