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 Quote Link to comment 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. Quote Link to comment 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 ~ Quote Link to comment 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) Quote Link to comment 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. Quote Link to comment 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.