regex - extract last group of numbers in a string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
markjohnson
Forum Newbie
Posts: 15
Joined: Sat Feb 07, 2009 8:36 pm

regex - extract last group of numbers in a string

Post by markjohnson »

Hi,

I have:

$string="this-is-my-uri--8271";

How can extract just the last group of numbers at the end, i.e. 8271?

Thanks
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: regex - extract last group of numbers in a string

Post by requinix »

Try exploding it on a hyphen and getting the last element in the returned array.
(Because I think a regular expression would be slower)
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Re: regex - extract last group of numbers in a string

Post by jayshields »

Use preg_match() if there's just one group of numbers, if there's more than one group and you want the last group then use preg_match_all() and grab the last element in the array of matches.

Code: Select all

/[0-9]+/
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: regex - extract last group of numbers in a string

Post by requinix »

jayshields wrote:if there's more than one group and you want the last group then use preg_match_all() and grab the last element in the array of matches.

Code: Select all

/[0-9]+/
Or just use preg_match with a different expression.

Code: Select all

/\d+$/
Post Reply