Jump to content

regex - extract last group of numbers in a string


markjohnson

Recommended Posts

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
Share on other sites

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
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.