markjohnson Posted June 21, 2009 Share Posted June 21, 2009 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 Link to comment https://forums.phpfreaks.com/topic/163162-regex-extract-last-group-of-numbers-in-a-string/ Share on other sites More sharing options...
nrg_alpha Posted June 21, 2009 Share Posted June 21, 2009 One way could be: $string="this-is-my-uri--8271"; preg_match('#[0-9]+$#', $string, $match); echo $match[0]; // Output: 8271 If it will always be certain to have 4 digits at the end, another possible solution could involve the use of substr: $numbers = substr($string, -4, 4); Depending on the circumstances, regex may not be needed. Link to comment https://forums.phpfreaks.com/topic/163162-regex-extract-last-group-of-numbers-in-a-string/#findComment-860869 Share on other sites More sharing options...
.josh Posted June 21, 2009 Share Posted June 21, 2009 ugh. beat me to it. you know nrg, i don't know if it's a good sign or a bad sign that our regex solutions usually always come out almost exactly the same. Well this is a simple example. Kind of hard to not come out the same. But i've noticed on more complex examples the same thing. Except you're partial to # I'm partial to ~ Link to comment https://forums.phpfreaks.com/topic/163162-regex-extract-last-group-of-numbers-in-a-string/#findComment-860871 Share on other sites More sharing options...
nrg_alpha Posted June 21, 2009 Share Posted June 21, 2009 CV, we both are pretty sound / comfortable with regex, so if our solutions are similar, I'm hoping that's a good sign (if not, then we're both more off base than we thought) Link to comment https://forums.phpfreaks.com/topic/163162-regex-extract-last-group-of-numbers-in-a-string/#findComment-860874 Share on other sites More sharing options...
markjohnson Posted June 21, 2009 Author Share Posted June 21, 2009 Thanks! It did the trick. One way could be: $string="this-is-my-uri--8271"; preg_match('#[0-9]+$#', $string, $match); echo $match[0]; // Output: 8271 If it will always be certain to have 4 digits at the end, another possible solution could involve the use of substr: $numbers = substr($string, -4, 4); Depending on the circumstances, regex may not be needed. Link to comment https://forums.phpfreaks.com/topic/163162-regex-extract-last-group-of-numbers-in-a-string/#findComment-860877 Share on other sites More sharing options...
nrg_alpha Posted June 21, 2009 Share Posted June 21, 2009 Glad to hear. You can flag this thread as solved. Link to comment https://forums.phpfreaks.com/topic/163162-regex-extract-last-group-of-numbers-in-a-string/#findComment-860882 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.